XSLT:使用来自祖先的兄弟节点的数据应用模板

XSLT: Applying a template with data from an ancestor's sibling node

我是 XPathXSLT 的新手,我正在将一个 XML 文档转换成另一个 XML 使用 XSLT 的文档。

以下代码为源文件的一部分:

<aggregateRoot>
   <orderRequest someAttribute="stuff">
       <!--more nodes-->
   </orderRequest>
   <order>
      <item>
        <template>
          <node>
             <image/>
          </node>
        </template>
      </item>
    </order>
<aggregateRoot>

这是我的 XSLT 的样子:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
    <!--A bunch of stuff that works already-->   
   <Orders>
      <xsl:for-each select="aggregateRoot/order">
         <!--More Nodes-->
         <xsl:for-each select="item/template">
             <Jobs>
                 <xsl:apply-templates select="//agregateRoot/orderRequest"/>   <!--PROBLEM AREA-->
             </Jobs>
         </xsl:for-each>
      </xsl:for-each>
   </Orders>
<xsl:template/>

<xsl:template match="aggregateRoot/orderRequest">
   <!--Grab data from orderRequest and its children-->
</xsl:template>

问题描述:

在上面的 XSLT 中,当我在 <Jobs> 节点内时,我试图应用一个基于 <orderRequest> 节点的模板,它是 [=14] 的兄弟节点=] 节点和主 <aggregateRoot> 节点的子节点。

我已经尝试了几十种组合来改变 selectmatch 语句的结构,但我无法访问 <orderRequest> 节点甚至无法获得第二个要触发的模板。

我发现您的 XSLT 存在两个问题和两个较小的问题:

  • 格式不正确(您的样本输入也不是)
  • 你拼错了"aggregate"
  • 您正在使用双斜杠,而您只需要一个斜杠
  • 您过度使用 for-each 而不是模板

一旦解决了前两个问题,XSLT 就可以工作了。这是已修复的所有 4 个问题:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="/">
    <Orders>
      <xsl:apply-templates select="aggregateRoot/order" />
    </Orders>
  </xsl:template>

  <xsl:template match="order">
    <xsl:apply-templates select="item/template" />
  </xsl:template>

  <xsl:template match="template">
    <Jobs>
      <xsl:apply-templates select="/aggregateRoot/orderRequest"/>
    </Jobs>
  </xsl:template>

  <xsl:template match="orderRequest">
    <xsl:value-of select="@someAttribute" />
  </xsl:template>
</xsl:stylesheet>

这会产生输出:

<Orders>
  <Jobs>stuff</Jobs>
</Orders>