You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从XML文件中提取<id_wert>等于1的所有<path>节点内容?

提取XML中符合条件的元素内容

需求对应逻辑

你需要实现类似SQL select path from xml where id = 1的功能,从XML中获取所有<id_wert>值为1的<path>元素内容。


方法1:用XPath直接查询

XPath是XML查询的标准方式,对应需求的表达式如下:

  • 如果XML中是<id_wert>节点://xml_export[id_wert='1']/path/text()
  • 你的样本XML里是<id>节点,调整为://xml_export[id='1']/path/text()

命令行工具实现(xmllint)

假设XML文件名为data.xml,执行:

xmllint --xpath "//xml_export[id='1']/path/text()" data.xml

输出:

\DATEN\00000001.003
\DATEN\00000001.005

方法2:Python标准库实现(xml.etree.ElementTree)

无需额外安装依赖,用Python自带库处理:

import xml.etree.ElementTree as ET

tree = ET.parse('data.xml')
root = tree.getroot()

for export in root.findall('xml_export'):
    id_node = export.find('id')
    if id_node is not None and id_node.text == '1':
        path_node = export.find('path')
        if path_node is not None:
            print(path_node.text)

执行后输出符合条件的路径。


方法3:Python lxml库实现(更灵活)

如果需要处理复杂XML结构,用lxml库更高效:

from lxml import etree

tree = etree.parse('data.xml')
# 替换id为id_wert以匹配你的实际需求
matching_paths = tree.xpath("//xml_export[id='1']/path/text()")
for path in matching_paths:
    print(path)

注意事项

如果你的实际XML中确实是<id_wert>而非样本里的<id>,只需将所有代码/表达式中的id替换为id_wert即可。

内容的提问来源于stack exchange,提问作者Aaron Erler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:01:13