如何使用python获取xml文件中的特定节点

Moa*_*ghi 5 python xml

我正在寻找一种获取特定标签的方法..来自一个非常大的xml文档,
例如内置模块中的python dom :

<AssetType longname="characters" shortname="chr" shortnames="chrs">
  <type>
    pub
  </type>
  <type>
    geo
  </type>
  <type>
    rig
  </type>
</AssetType>

<AssetType longname="camera" shortname="cam" shortnames="cams">
  <type>
    cam1
  </type>
  <type>
    cam2
  </type>
  <type>
    cam4
  </type>
</AssetType>
Run Code Online (Sandbox Code Playgroud)

我想检索具有属性(longname ="characters")的AssetType节点的子节点的值,以便得到结果'pub','geo','rig'
请记住我
提前有超过1000个<AssetType>节点而不是x

esw*_*ald 6

如果您不介意将整个文档加载到内存中:

from lxml import etree
data = etree.parse(fname)
result = [node.text.strip() 
    for node in data.xpath("//AssetType[@longname='characters']/type")]
Run Code Online (Sandbox Code Playgroud)

您可能需要删除标签开头的空格才能完成这项工作。


Ten*_*she 5

假设您的文档被调用assets.xml并具有以下结构:

<assets>
    <AssetType>
        ...
    </AssetType>
    <AssetType>
        ...
    </AssetType>
</assets>
Run Code Online (Sandbox Code Playgroud)

然后,您可以执行以下操作:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
root = tree.parse("assets.xml")
for assetType in root.findall("//AssetType[@longname='characters']"):
    for type in assetType.getchildren():
        print type.text
Run Code Online (Sandbox Code Playgroud)