使用 Python ElementTree 解析 XML

Pra*_*n93 3 python xml elementtree

我有以下格式的 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>
Run Code Online (Sandbox Code Playgroud)

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

小智 12

来自ElementTree 文档

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

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()
Run Code Online (Sandbox Code Playgroud)

或者直接从一个字符串:

root = ET.fromstring(country_data_as_string)
Run Code Online (Sandbox Code Playgroud)

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

for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)
Run Code Online (Sandbox Code Playgroud)

翻译成:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

14/11/2017
14/11/2017
{'LV': '0'} The quick
{'LV': '1'} brown
{'LV': '2'} fox
{'LV': '0'} The lazy
{'LV': '1'} fox
Run Code Online (Sandbox Code Playgroud)


Mis*_*erT 5

你没有具体说明你想使用什么,所以我推荐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)
Run Code Online (Sandbox Code Playgroud)

输出:['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)
Run Code Online (Sandbox Code Playgroud)

输出:14/11/2017 14/11/2017 敏捷的棕色狐狸 懒惰的狐狸

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