0

很抱歉问这个问题,尽管有很多关于这个的话题。但现在看来,它们都不能满足我的需求。

我有一个 xml 文件。

<RestaurantList>
 <Restaurant id="100000">
  <Url>http://www.example.com/</Url>
  <Name>TestRestaurant</Name>
  <Description>
   <Text>This restaurant has a generous selection of fine wines</Text>
  </Description>
 </Restaurant>
 <Restaurant id="100001">
  <Url>http://www.example.com/</Url>
  <Name>TestRestaurant1</Name>
  <Description>
   <Text>This restaurant1 has a generous selection of fine wines</Text>
  </Description>
 </Restaurant>
</RestaurantList>

我想遍历所有元素并将其中一些元素保存到数据库中。我看到了一些类似lxmlxml在 python 中的库。我试过这个:

import xml.etree.ElementTree as ET
file = ET.parse(settings.MEDIA_ROOT+'\\table.xml')
    rests = file.xpath('//Restaurant')
    for each in rests:
        self.stdout.write(each)

但我收到ElementTree has no object attribute xpath错误,

这样做的最好方法是什么?提前感谢吨

4

2 回答 2

1

您的示例代码非常适合我使用 Python 2.7.4 和 lxml 3.2.3,该xpath()方法返回一个包含这两个Restaurant元素的列表。如果您的 XML 解析器坚持认为 XML 文件格式正确,则可能是您输入了错误的文件,或者文件以无法识别的编码(例如 UTF-16)保存。

要对此进行调试,请尝试打印open(settings.MEDIA_ROOT+'\\table.xml').read()并查看输出是否看起来像有效的 XML。如果对 XML 的正确性有疑问,最好也使用独立工具(例如xmllint.

于 2013-10-13T20:38:06.270 回答
0

我这样做了:

datei = ET.parse(settings.MEDIA_ROOT+'\\table.xml')
    rests = datei.getroot()
    for each in rests:
      #do something with tags

无论如何感谢您的答案和意见..

于 2013-10-14T08:44:53.270 回答