更新时间:2022-11-28 16:19:21
就像@michael.hor257k 所说的,从概念上讲,这个问题与您之前的问题相同.我想你只是没有理解这个概念.希望我的示例中的注释会有所帮助.
Like @michael.hor257k said, conceptually this question is the same as your previous question. I think you're just not understanding the concept. Hopefully the comments in my example will help.
如果我正确理解了这个问题,您希望基于 ParentID
将 order
元素嵌套在其父"order
元素中.由于我们基于 ParentID,这就是我们将用于我们的密钥...
If I understand the question correctly, you want to nest order
elements inside of their "parent" order
element based on ParentID
. Since we're basing it on the ParentID, that's what we'll use for our key...
XML 输入
<main>
<order>
<ID>123</ID>
<Name>ABC</Name>
</order>
<order>
<ID>4556</ID>
<Name>AAA</Name>
<ParentID>123</ParentID>
</order>
</main>
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<!--Create a key containing order elements that contain a non-empty ParentID.-->
<xsl:key name="orderByParentId" match="order[string(ParentID)]" use="ParentID"/>
<!--Identity transform (https://www.w3.org/TR/xslt#copying)-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/main">
<xsl:copy>
<!--To get the high level order elements, only apply-templates when order
does not contain a non-empty ParentID child.-->
<xsl:apply-templates
select="@*|order[not(string(ParentID))]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="order">
<xsl:copy>
<!--Don't apply-templates to ParentID; we don't want to keep those.
Do apply-templates to the key 'orderByParentId' when the key matches
the current order's ID child.-->
<xsl:apply-templates
select="@*|*[not(self::ParentID)]|key('orderByParentId',ID)"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
输出
<main>
<order>
<ID>123</ID>
<Name>ABC</Name>
<order>
<ID>4556</ID>
<Name>AAA</Name>
</order>
</order>
</main>