使用 elementtree,是否有一种简单的方法来解析整个 xml 文档,除了那些位于具有某些特定属性值的节点上的文本。例如,我想解析文件,除了 when attribute name="Liechtenstein" 和 when attribute month="08"
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<language>english</language>
<currency>1.21$/kg</currency>
<gdppc month="06">141100</gdppc>
<gdpnp month="10">2.304e+0150</gdpnp>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<language>english</language>
<currency>4.1$/kg</currency>
<gdppc month="05">59900</gdppc>
<gdpnp month="08">5.2e-015</gdpnp>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Lahore">
<rank updated="yes">8</rank>
<language>Pertr</language>
<currency>7.3$/kg</currency>
<gdppc month="010">34000</gdppc>
<gdpnp month="099">3.4e+015</gdpnp>
<neighbor name="Peru" direction="N"/>
</country>
</data>
基于以上,我想返回以下5,english,4.1$/kg,59900, 8, Pertr, 7.3$/kg, 34000, 3.4e+015 。我觉得可以使用 iterparse 但我不知道该怎么做。 感谢您的建议
请您参考如下方法:
- 使用
xml.etree.ElementTree模块解析XML内容。 - 使用
getiterator()方法只迭代country标签。 - 验证
country标签。 - 通过
getchildren()方法在选定的country标签上迭代 child 。 - 验证子项以进行月份验证。
- 在 tmp 列表中添加值。
- 将 tmp 附加到主要结果列表。
代码:
import xml.etree.ElementTree as PARSER
root = PARSER.fromstring(data)
result = []
for i in root.getiterator("country"):
if "name" in i.attrib and i.attrib["name"] not in ["Liechtenstein"]:
tmp = []
for j in i.getchildren():
if "month" in j.attrib:
if j.attrib["month"] not in ["08"]:
if j.text:
tmp.append(j.text)
else:
if j.text:
tmp.append(j.text)
result.append(tmp)
print "result:-", result
输出:
:~/workspace/vivek$ python test3.py
result:- [['5', 'english', '4.1$/kg', '59900'], ['8', 'Pertr', '7.3$/kg', '34000', '3.4e+015']]
通过lxml模块
使用xpath()方法获取目标country标签。
代码:
import lxml.html as PARSER
root = PARSER.fromstring(data)
result = []
print "debug 1 list of country: ", root.xpath("//country[@name!='Liechtenstein']")
for i in root.xpath("//country[@name!='Liechtenstein']"):
tmp = []
for j in i.getchildren():
if "month" in j.attrib:
if j.attrib["month"] not in ["08"]:
if j.text:
tmp.append(j.text)
else:
if j.text:
tmp.append(j.text)
result.append(tmp)
print "result:-", result
结果:
:~/workspace/vtestproject$ python test3.py
debug 1 list of country: [<Element country at 0xb724da04>, <Element country at 0xb7257cac>]
result:- [['5', 'english', '4.1$/kg', '59900'], ['8', 'Pertr', '7.3$/kg', '34000', '3.4e+015']]
