如何在Python中没有模式的情况下读取和解析XML?

Leo*_*nid 0 python xml xml-parsing

有没有一种方法可以在没有模式的情况下在Python中读取XML文档?在我的用例中有一个类似于以下的文件.

<people>
    <human>
      <weight>75</weight>
      <height>174</height>
    </human>
    <human>
      <weight>89</weight>
      <height>187</height>
    </human>
</people>
Run Code Online (Sandbox Code Playgroud)

我需要从中提取一个数组weight.它可以通过字符串操作轻松完成,但必须有一个更简洁的方法来使用XML解析器吗?

小智 7

您可以使用ElementTree(包含在python标准库中)并执行以下操作:

import xml.etree.ElementTree
tree = xml.etree.ElementTree.parse("foo.xml")
myArray = [int(x.text) for x in tree.getroot().findall("human/weight")]
Run Code Online (Sandbox Code Playgroud)