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

XSL 2.0中如何在for-each中获取数组项值拼接href?

XSL 2.0 中如何关联外部XML文档URL与节点属性

我是XSL新手,对for-each的工作原理可能存在误解。目前我的for-each可正常从数组提供的URL对应的XML文档中获取每个item节点,但无法将数组中对应XML文档的URL与item的href属性拼接。请问这是否可行?代码中标注为WHAT_GOES_HERE的位置应填写什么内容?(使用XSL 2.0)

相关代码示例

<xsl:variable name="array" as="element()*">
    <item>https://www.example.com/_resources/data/blogs.xml</item> <!--item 1-->
    <item>https://www.example.com/_resources/data/blogs2.xml</item> <!--item 2--> 
</xsl:variable>

<xsl:for-each select="$array/document(.)/items/item">
   <item>
       <xsl:attribute name="href" select="concat(WHAT_GOES_HERE?,@href)"/>
   </item>
</xsl:for-each>

XML示例(外部文档结构)

<items>
<item href="/news-and-events/news/2024-02-amplify-stem-course-based-undergraduate-research-experience.aspx" dsn="blogs">
      <homehero>true</homehero>
      <pubDate>02/19/2024</pubDate>
      <title>Example TItle</title>
      <description>Example</description>
      <highlights/>
      <author>Author Name</author>
      <hero-image>
        <img src="" alt=""/>
      </hero-image>
      <image>
        <img src="/_assets/images/news/2024/jinjie-square.JPG" alt="Four women look at computers in a lab"/>
      </image>
      <tags>
        <tag>lab</tag>
      </tags>
    <searchtags>lab</searchtags>
    </item>
</items>

预期实现效果

<item href="https://www.example.com/_resources/data/blogs.xml/news-and-events/news/2024-02-amplify-stem-course-based-undergraduate-research-experience.aspx"/>
<item href="https://www.example.com/_resources/data/blogs2.xml/news-and-events/news/2024-02-amplify-stem-course-based-undergraduate-research-experience.aspx"/>

解决方案

这完全可行,问题在于原代码的for-each直接跳转到了外部XML的item节点,丢失了原数组中URL的上下文。你需要通过嵌套for-each来保留URL的上下文:

修改后的代码

<xsl:variable name="array" as="element()*">
    <item>https://www.example.com/_resources/data/blogs.xml</item> <!--item 1-->
    <item>https://www.example.com/_resources/data/blogs2.xml</item> <!--item 2--> 
</xsl:variable>

<!-- 先遍历数组中的每个URL节点 -->
<xsl:for-each select="$array">
    <!-- 保存当前URL到变量,方便内部引用 -->
    <xsl:variable name="current-source-url" select="."/>
    <!-- 再遍历该URL对应的XML文档中的item节点 -->
    <xsl:for-each select="document(.)/items/item">
       <item>
           <xsl:attribute name="href" select="concat($current-source-url, @href)"/>
       </item>
    </xsl:for-each>
</xsl:for-each>

原理说明

  • 外层for-each遍历原数组的每个URL节点,此时上下文是<item>https://xxx.xml</item>元素,用$current-source-url变量保存其文本值(即XML文档URL)。
  • 内层for-each调用document(.)加载对应URL的XML,遍历其中的items/item节点,此时可以直接引用外层的$current-source-url变量,和当前节点的@href属性拼接。

如果你想要更简洁的写法,也可以使用xsl:apply-templates配合模式,但嵌套for-each是最直观易懂的方式,适合新手理解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:02:05