How to combine XML elements using XSLT

2019-08-01 08:29发布

I have the following XML:

<root>
<section>
    <item name="a">
        <uuid>1</uuid>
    </item>
</section>
<section>
    <item name="b">
        <uuid>2</uuid>
    </item>
</section>
</root>

I would like to transform it into the following XML:

<root>
<section>
    <item name="a">
        <uuid>1</uuid>
    </item>
    <item name="b">
        <uuid>2</uuid>
    </item>
</section>
</root>

Thanks in advance.

Update.

A slightly different example contains additional elements and attributes.

Input:

<root age="1">
<description>some text</description>
<section>
    <item name="a">
        <uuid>1</uuid>
    </item>
</section>
<section>
    <item name="b">
        <uuid>2</uuid>
    </item>
</section>
</root>

I would like to transform it into:

<root age="1">
<description>some text</description>
<section>
    <item name="a">
        <uuid>1</uuid>
    </item>
    <item name="b">
        <uuid>2</uuid>
    </item>
</section>
</root>

标签: xml xslt
1条回答
闹够了就滚
2楼-- · 2019-08-01 09:22

Following Xsl should work:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="section item"/>
    <xsl:template match="/root">
        <root>
            <section>
                <xsl:apply-templates select="section"/>
            </section>
        </root>
    </xsl:template>

    <xsl:template match="item">
        <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>

It gives:

<root>
   <section>
      <item name="a">
         <uuid>1</uuid>
      </item>
      <item name="b">
         <uuid>2</uuid>
      </item>
  </section>
</root>

Update:

For second example you can use following Xsl:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="root item"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
   </xsl:template>

   <xsl:template match="description">
       <xsl:copy-of select="."/>
       <section>
           <xsl:apply-templates select="following-sibling::section/item"/>
       </section>
   </xsl:template>

   <xsl:template match="section" />

   <xsl:template match="item">
      <xsl:copy-of select="."/>
   </xsl:template>

</xsl:stylesheet>
查看更多
登录 后发表回答