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

标签 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>

我想检索获得属性 (longname= "characters") 的 AssetType 节点的子节点的值 得到 'pub','geo','rig'
的结果 请记住我有超过 1000 个 节点
提前谢谢

最佳答案

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

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

您可能需要删除标签开头的空格才能使其正常工作。

关于python - 如何使用python获取xml文件中的特定节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2230677/

相关文章:

Python: AttributeError: 'module' 对象没有属性 'WD_BREAK'

android - 使用支持库的 XML 字体

android - 如何在相对布局中排列图像

xml - 通过XPath选择XML节点时如何使用正则表达式?

python - tensorflow 线性回归误差爆炸

python - 使用 python Spark 读取和分组数据以获取计数

python - 如何在 Pandas 数据框中保留每组的前 3 行?

python - 如何让 `pip search` 与我的本地 pypi 服务器一起工作?

python - 如何在 lxml 中使用带有 find/findall 的 xml 命名空间?

xml - Xpath 使用 [1] 时选择 1+ 个节点