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

如何用XPath提取无命名空间及前缀的XML标签值,匹配TextId为ZC01的内容

解决方案

第一步:正确定位目标节点

你之前用local-name()未成功通常是筛选逻辑写法有误,以下是不需要提前注册命名空间、直接通过节点名定位目标TextLine的XPath表达式:

//*[local-name()='properties' and *[local-name()='TextId' and text()='ZC01']]/*[local-name()='TextLine']

第二步:去除命名空间前缀与声明

你拿到的结果带d:前缀和xmlns:d声明,是XML节点序列化时默认保留原命名空间属性导致的,根据使用场景不同可以选择对应处理方案:

  • 在线XPath工具/轻量提取场景:直接用XPath拼接目标字符串,一步得到结果:
    concat('<TextLine>', //*[local-name()='properties' and *[local-name()='TextId' and text()='ZC01']]/*[local-name()='TextLine']/text(), '</TextLine>')
    
  • Python lxml 场景:拿到节点后修改标签名、清除命名空间属性再序列化:
    from lxml import etree
    # 此处省略XML加载、节点定位逻辑
    target_node = root.xpath("//*[local-name()='properties' and *[local-name()='TextId' and text()='ZC01']]/*[local-name()='TextLine']")[0]
    # 替换标签名为无前缀的本地名
    target_node.tag = etree.QName(target_node).localname
    # 清除所有命名空间声明属性
    for attr in list(target_node.attrib):
        if attr.startswith("xmlns:"):
            del target_node.attrib[attr]
    # 输出结果
    print(etree.tostring(target_node, encoding="unicode"))
    
  • Java DOM 场景:调用Document.renameNode()方法将节点重命名为无命名空间的TextLine,再移除对应xmlns属性即可。

内容的提问来源于stack exchange,提问作者Sugata Bagchi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:18:04