Python XML 仅获取直接子元素

标签 python xml python-3.x

我有一个如下的 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<EDoc CID="1000101" Cname="somename" IName="iname" CSource="e1" Version="1.0">
<RIGLIST>
    <RIG RIGID="100001" RIGName="RgName1">
          <ListID>
            <nodeA nodeAID="1000011" nodeAName="node1A" nodeAExtID="9000011" />
            <nodeA nodeAID="1000012" nodeAName="node2A" nodeAExtID="9000012" />
            <nodeA nodeAID="1000013" nodeAName="node3A" nodeAExtID="9000013" />
            <nodeA nodeAID="1000014" nodeAName="node4A" nodeAExtID="9000014" />
            <nodeA nodeAID="1000015" nodeAName="node5A" nodeAExtID="9000015" />
            <nodeA nodeAID="1000016" nodeAName="node6A" nodeAExtID="9000016" />
            <nodeA nodeAID="1000017" nodeAName="node7A" nodeAExtID="9000017" />
          </ListID>
        </RIG>
    <RIG RIGID="100002" RIGName="RgName2">
          <ListID>
            <nodeA nodeAID="1000021" nodeAName="node1B" nodeAExtID="9000021" />
            <nodeA nodeAID="1000022" nodeAName="node2B" nodeAExtID="9000022" />
            <nodeA nodeAID="1000023" nodeAName="node3B" nodeAExtID="9000023" />
          </ListID>
        </RIG>
</RIGLIST>
</EDoc>

我需要搜索节点值 RIGName,如果找到匹配,则打印出 nodeAName 的所有值

示例: 搜索 RIGName = "RgName2"应将所有值打印为 node1B、node2B、node3B

到目前为止,我只能得到第一部分,如下所示:

import xml.etree.ElementTree as eT
import re

xmlfilePath  = "Path of xml file"

tree = eT.parse(xmlfilePath)
root = tree.getroot()

for elem in root.iter("RIGName"):
        # print(elem.tag, elem.attrib)
            if re.findall(searchtxt, elem.attrib['RIGName'], re.IGNORECASE):
                print(elem.attrib)
                count += 1

如何仅获取直接子节点值?

最佳答案

xml.etree 切换到 lxml由于 much better XPath query language support 将为您提供一种一次性完成此操作的方法:

In [1]: from lxml import etree as ET

In [2]: tree = ET.parse('input.xml')

In [3]: root = tree.getroot()

In [4]: root.xpath('//RIG[@RIGName = "RgName2"]/ListID/nodeA/@nodeAName')
Out[4]: ['node1B', 'node2B', 'node3B']

关于Python XML 仅获取直接子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51353867/

相关文章:

python - 求解所有可能的映射

python - 在不保存的情况下在 Jupyter Notebook 中打开 base64 字符串图像

python - 在 xml 标签的文本元素中提取标签

python - 如何修改这段代码,使其以相反的顺序打印输入字符串?

python - Python 的舍入问题

python - 如何在 python 中重新格式化字符串?

java - Jackson XML - 使用 namespace 前缀反序列化 XML

html - 在 R 中解析 HTML 文件

html - 使用 Flask 作为后端时,在 div 的文本中呈现换行符?

python - 如何不打印命令输出?