如何使用 XSLT 组合 XML 元素 [英] How to combine XML elements using XSLT

查看:31
本文介绍了如何使用 XSLT 组合 XML 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 XML:

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

我想将其转换为以下 XML:

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>

提前致谢.

更新.

一个稍微不同的例子包含额外的元素和属性.

A slightly different example contains additional elements and attributes.

输入:

<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>

我想把它转换成:

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

推荐答案

以下 Xsl 应该可以:

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>

它给出:

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

更新:

对于第二个示例,您可以使用以下 Xsl:

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>

这篇关于如何使用 XSLT 组合 XML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆