XML解析器python无法获取元素

时间:2013-07-14 20:16:26

标签: python xml elementtree

python中的

etree.ElementTree包解析我的xml文件,但似乎没有这样做。

我的xml文件层次结构如下:     根   < - > 配置数据             <>             源文件            < - >           file object1 object2 ... etc。

当我使用print self.xml_root.findall(“。\ config”)时,我只得到“[]”,这是一个空列表, 感谢

1 个答案:

答案 0 :(得分:2)

如果字符串中确实有'.\config',那就是问题所在。这是一个字符串文字,使用\c作为其中一个字符。即使您有'.\\config'r'.\config',两者都指定了字面反斜杠,但仍然是错误的:

$ cat eleme.py
import xml.etree.ElementTree as ET

root = ET.fromstring("""
<root>
  <config>
    source
  </config>
  <config>
    source
  </config>
</root>""")

print r'using .\config', root.findall('.\config')
print r'using .\\config', root.findall('.\\config')
print 'using ./config', root.findall('./config')
$ python2.7 eleme.py 
using .\config []
using .\\config []
using ./config [<Element 'config' at 0x8017a8610>, <Element 'config' at 0x8017a8650>]
相关问题