使用 Python ElementTree 解析 XML

新手上路,请多包涵

我有一个以下格式的 XML 文档

<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>

如何从 H 标签内的“D”中提取文本以及 F 标签内的所有文本。

原文由 Pragyan93 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 562
2 个回答

来自 ElementTree 文档

我们可以通过从文件中读取来导入这些数据:

 import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()

或者直接从字符串:

 root = ET.fromstring(country_data_as_string)

稍后在同一页面中,20.5.1.4。寻找有趣的元素:

 for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)

翻译成:

 import xml.etree.ElementTree as ET

root = ET.fromstring("""
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>""")
# root = tree.getroot()
for h in root.iter("H"):
    print (h.attrib["D"])
for f in root.iter("F"):
    print (f.attrib, f.text)

输出:

 14/11/2017
14/11/2017
{'LV': '0'} The quick
{'LV': '1'} brown
{'LV': '2'} fox
{'LV': '0'} The lazy
{'LV': '1'} fox

原文由 Hirabayashi Taro 发布,翻译遵循 CC BY-SA 3.0 许可协议

你没有具体说明你到底想使用什么,所以我推荐 lxml for python。为了获得你想要的价值,你有更多的可能性:

有一个循环:

 from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
text = []
for element in root:
   text.append(element.get('D',None))
     for child in element:
       for grandchild in child:
         text.append(grandchild.text)
print(text)

输出:[‘14/11/2017’, ‘The quick’, ‘brown’, ‘fox’, ‘14/11/2017’, ‘The lazy’, ‘fox’]

使用 xpath:

 from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
D = root.xpath("./H")
F = root.xpath(".//F")

for each in D:
  print(each.get('D',None))

for each in F:
  print(each.text)

输出: 14/11/2017 14/11/2017 The quick brown fox The lazy fox

两者都有自己的优势,但给你一个很好的起点。我推荐 xpath ,因为它在缺少值时给你更多的自由。

原文由 MisterT 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题