XSLT 将平面 xml 结构转变为分层结构

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

我需要一个 xslt,它可以采用平面 xml 并将其转换为分层结构。 来源是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:FlatInfo xmlns:ns0="http://mynamespace.com">
    <Header>
        <OrderNo>100</OrderNo>
    </Header>
    <Item>
        <ItemNo>1</ItemNo>
        <Product>Slime</Product>
        <Quantity>2</Quantity>
    </Item>
    <Item>
        <ItemNo>2</ItemNo>
        <Product>Gunge</Product>
        <Quantity>4</Quantity>
    </Item>
    <Header>
        <OrderNo>102</OrderNo>
    </Header>
    <Item>
        <ItemNo>1</ItemNo>
        <Product>Sludge</Product>
        <Quantity>55</Quantity>
    </Item>
</ns0:FlatInfo>

这需要变成:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:TreeInfo xmlns:ns0="http://mynamespace.com">
    <Header>
        <OrderNo>100</OrderNo>
        <Item>
            <ItemNo>1</ItemNo>
            <Product>Slime</Product>
            <Quantity>2</Quantity>
        </Item>
        <Item>
            <ItemNo>2</ItemNo>
            <Product>Gunge</Product>
            <Quantity>4</Quantity>
        </Item>
    </Header>
    <Header>
        <OrderNo>102</OrderNo>
        <Item>
            <ItemNo>1</ItemNo>
            <Product>Sludge</Product>
            <Quantity>55</Quantity>
        </Item>
    </Header>
</ns0:TreeInfo>

将项目链接到标头的唯一因素是它们在源 xml 中的输出顺序。 请有人建议实现此目标的最佳方法。

xslt 新手,正在努力使其工作

xslt xslt-2.0
1个回答
0
投票

本质上是

<xsl:template match="*:FlatInfo">
  <xsl:for-each-group select="*" group-starting-with="Header">
    <Header>
      <xsl:copy-of select="current-group()/(*/OrderNo, Item)"/>
    </Header>
  </xsl:for-each-group>
</xsl:template>
© www.soinside.com 2019 - 2024. All rights reserved.