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

使用XPath提取XML中特定Key对应的Value值

用XPath提取XML中特定Key对应的Value值

没问题,我来帮你搞定这个XPath提取的事儿!先看看你提供的XML结构:

<?xml version="1.0" encoding="UTF-8"?>
<OMRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ApplicationId>User</ApplicationId>
  <BusinessProcessId>GiftCard</BusinessProcessId>
  <Data>
    <Item>
      <Key>fsf_addr</Key>
      <Value>Lancelot</Value>
    </Item>
    <Item>
      <Key>email_addr</Key>
      <Value>T...</Value>
    </Item>
  </Data>
</OMRequest>

1. 提取单个特定Key对应的Value

如果你想获取某个指定Key(比如fsf_addr)对应的Value,可以用下面的XPath表达式:

//OMRequest/Data/Item[Key='fsf_addr']/Value/text()
  • //OMRequest/Data/Item:定位到XML中所有的Item节点(它们嵌套在Data下,属于根节点OMRequest)
  • [Key='fsf_addr']:筛选出子节点Key的文本等于fsf_addr的那个Item
  • /Value/text():取出该Item下Value节点的文本内容

要是想提取email_addr的Value,只需要把表达式里的fsf_addr换成email_addr就行。

2. 批量提取所有Key-Value对

如果需要一次性获取所有的Key和Value组合,可以用这个XPath来定位所有Item节点:

//OMRequest/Data/Item

之后你可以遍历每个Item节点,分别提取Key和Value的文本内容。比如用Python的lxml库实现的话,代码示例如下:

from lxml import etree

# 你的XML内容
xml_content = """<?xml version="1.0" encoding="UTF-8"?>
<OMRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ApplicationId>User</ApplicationId>
  <BusinessProcessId>GiftCard</BusinessProcessId>
  <Data>
    <Item>
      <Key>fsf_addr</Key>
      <Value>Lancelot</Value>
    </Item>
    <Item>
      <Key>email_addr</Key>
      <Value>T...</Value>
    </Item>
  </Data>
</OMRequest>"""

tree = etree.fromstring(xml_content)
# 获取所有Item节点
items = tree.xpath("//OMRequest/Data/Item")
for item in items:
    key = item.xpath("./Key/text()")[0]
    value = item.xpath("./Value/text()")[0]
    print(f"{key}: {value}")
# 输出:
# fsf_addr: Lancelot
# email_addr: T...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:53:24