XSL - 如何选择所有祖先到根,而不是兄弟节点

问题描述 投票:0回答:1

我有一个 xml 有效载荷

<Root>

    <Header>
        <Name>B</Name>
    </Header>
    <Item>
        <Id>10</Id>
        <Description>Item10</Description>
    </Item>
    <Item>
        <Id>20</Id>
        <Description>Item20</Description>
    </Item>
    <Package>
        <Id>A</Id>
    </Package>
    <Package>
        <Id>B</Id>
    </Package>
    <Package>
        <Id>C</Id>
    </Package>
</Root>

对于每个包,我试图将当前包的所有祖先的整个消息输出到它的根,而不是它的后续兄弟节点(其他包)。

期望的输出:

`

<Root>

    <Header>
        <Name>B</Name>
    </Header>
    <Item>
        <Id>10</Id>
        <Description>Item10</Description>
    </Item>
    <Item>
        <Id>20</Id>
        <Description>Item20</Description>
    </Item>
    <Package>
        <Id>A</Id>
    </Package>

</Root>
<Root>

    <Header>
        <Name>B</Name>
    </Header>
    <Item>
        <Id>10</Id>
        <Description>Item10</Description>
    </Item>
    <Item>
        <Id>20</Id>
        <Description>Item20</Description>
    </Item>

    <Package>
        <Id>B</Id>
    </Package>

</Root>
<Root>

    <Header>
        <Name>B</Name>
    </Header>
    <Item>
        <Id>10</Id>
        <Description>Item10</Description>
    </Item>
    <Item>
        <Id>20</Id>
        <Description>Item20</Description>
    </Item>

    <Package>
        <Id>C</Id>
    </Package>
</Root>
`

但我收到 3 条消息,包括每条消息中的所有包裹。

这是我的代码


<?xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">

<xsl:template match="/">
<Messages>
        <xsl:for-each select="//Package">
            <xsl:copy-of select="/*[not(following-sibling::*)]" />
        </xsl:for-each>
    </Messages>
</xsl:template>

我做错了什么?谢谢你的建议。

xslt nodes siblings
1个回答
0
投票

要得到你展示的结果(不是你描述的结果),你可以简单地做:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/Root">
    <xsl:variable name="common" select="*[not(self::Package)]" />
    <xsl:for-each select="Package">
        <Root>
            <xsl:copy-of select="$common"/>
            <xsl:copy-of select="."/>
        </Root>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

但请注意,此结果是一个 XML 片段,而不是一个格式良好的 XML 文档,因为它缺少单个根元素。

© www.soinside.com 2019 - 2024. All rights reserved.