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

XSLT 2.0中如何访问存储在变量里的节点集子元素?

XSLT 2.0变量访问子元素问题排查

问题场景

在XSLT 2.0中尝试将XML元素存入变量后,无法通过变量访问其子元素。预期输出PO BOY 123但实际无输出,仅直接输出变量时能获取所有文本内容。

输入XML

<wd:Report_Data xmlns:wd="urn:com.workday/bsvc">
   <wd:Report_Entry>
      <wd:Employee_ID>123</wd:Employee_ID>
      <wd:Primary_Address>
         <wd:Address_Line_1>PO BOY 123</wd:Address_Line_1>
         <wd:Address_Line_2>12345 Road Street</wd:Address_Line_2>
         <wd:City>CityTown</wd:City>
         <wd:Use_For>
            <wd:type>PHYSICAL_ADDRESS</wd:type>
         </wd:Use_For>
      </wd:Primary_Address>
   </wd:Report_Entry>
</wd:Report_Data>

原转换代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wd="urn:com.workday/bsvc">
    <xsl:output method="text" omit-xml-declaration="yes"/>
    
    <xsl:template match="/">
        <xsl:apply-templates select="wd:Report_Data/wd:Report_Entry"/>
    </xsl:template>
    
    <xsl:template match="wd:Report_Entry">
        <xsl:variable name="PrimaryAddress">
            <xsl:copy-of select="wd:Primary_Address"/>
        </xsl:variable>
        <xsl:value-of select="$PrimaryAddress/wd:Address_Line_1"/>
    </xsl:template>
    
</xsl:stylesheet>

问题原因

当前变量声明方式会将<xsl:copy-of>的结果包装为文档节点存储,而非直接存储wd:Primary_Address元素节点。此时$PrimaryAddress指向文档节点,直接使用$PrimaryAddress/wd:Address_Line_1会在文档节点的子节点中查找目标元素,但文档节点的子节点是wd:Primary_Address,路径不匹配导致无输出。

解决方案

方案1:直接绑定元素节点(推荐)

无需使用<xsl:copy-of>,直接通过select属性将变量绑定到目标元素节点,变量存储元素本身后可直接访问其子元素:

<xsl:template match="wd:Report_Entry">
    <xsl:variable name="PrimaryAddress" select="wd:Primary_Address"/>
    <xsl:value-of select="$PrimaryAddress/wd:Address_Line_1"/>
</xsl:template>

方案2:调整路径访问文档节点内的元素

若因业务需求必须使用<xsl:copy-of>(如复制并修改节点后存储),需调整路径先定位到文档节点下的wd:Primary_Address元素,再访问其子元素:

<xsl:template match="wd:Report_Entry">
    <xsl:variable name="PrimaryAddress">
        <xsl:copy-of select="wd:Primary_Address"/>
    </xsl:variable>
    <xsl:value-of select="$PrimaryAddress/wd:Primary_Address/wd:Address_Line_1"/>
</xsl:template>

两种方案均可得到预期输出PO BOY 123。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:27:06