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

如何用XSLT提取p1为Orange对应的p2值并填充到variablePrint标签

用XSLT提取指定水果对应值替换标签的解决方案

假设你的XML结构如下(需确保命名空间一致)

<root xmlns:h="http://example.com/ns">
  <h:fruit>
    <h:p1>Apple</h:p1>
    <h:p2>Red</h:p2>
  </h:fruit>
  <h:fruit>
    <h:p1>Orange</h:p1>
    <h:p2>OrangeColor</h:p2>
  </h:fruit>
  <h:fruit>
    <h:p1>Banana</h:p1>
    <h:p2>Yellow</h:p2>
  </h:fruit>
  <h:variablePrint>原固定值</h:variablePrint>
</root>

修改后的XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:h="http://example.com/ns">
  <!-- 复制原XML中无需修改的所有节点 -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- 替换<h:variablePrint>内容为目标值 -->
  <xsl:template match="h:variablePrint">
    <h:variablePrint>
      <!-- 定位到h:p1为Orange的h:fruit节点,提取对应h:p2的文本 -->
      <xsl:value-of select="//h:fruit[h:p1='Orange']/h:p2"/>
    </h:variablePrint>
  </xsl:template>
</xsl:stylesheet>

关键说明

  1. 命名空间一致性:XSLT里必须声明和XML完全一致的命名空间(xmlns:h="..."),否则无法匹配到带<h:前缀的节点。
  2. 身份转换模板:match="@*|node()"的模板负责复制原XML中所有不需要修改的内容,保证其他节点不受影响。
  3. XPath定位逻辑://h:fruit[h:p1='Orange']/h:p2 的作用是:
    • //h:fruit:遍历XML中所有<h:fruit>节点
    • [h:p1='Orange']:筛选出子节点<h:p1>文本等于Orange的节点
    • /h:p2:提取这些节点下的<h:p2>文本内容
  4. 多匹配场景处理:如果存在多个<h:p1>为Orange的节点,默认只取第一个匹配的<h:p2>值。若要输出所有匹配值,XSLT 2.0及以上版本可以用以下写法:
    <xsl:value-of select="//h:fruit[h:p1='Orange']/h:p2" separator=", "/>
    
    这样会把所有匹配值用逗号分隔输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 01:30:08