2012-04-04 87 views
2

结合我有下面输入XML:如何复杂的XML元素使用XSLT

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

我想将它转变成以下XML:

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

在此先感谢。

+0

什么是改造它的规则?将所有部分的所有孩子放在一个部分? – hroptatyr 2012-04-04 09:10:04

+0

@hroptatyr你是对的。将所有部分的所有孩子放入一个部分 – 2012-04-04 09:18:32

+1

重复? http://stackoverflow.com/questions/10007021/how-to-combine-xml-elements-using-xslt – ceving 2012-04-04 09:51:39

回答

1

一种更简单和更短的解决方案

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

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

<xsl:template match="section[1]"> 
    <section> 
    <xsl:apply-templates select="../section/node()"/> 
    </section> 
</xsl:template> 

<xsl:template match="section[position() > 1]"/> 
</xsl:stylesheet> 

当这种变换所提供的XML文档应用:

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

感谢@Dimitre Novatchev它的工作原理。这真是优雅的解决方案。你能否提供关于第[1]节和[第(位置)]第1节的简短说明 – 2012-04-04 13:12:01

+0

@SashaKorman:'section [1]'是第一节(其父节点)的匹配模式。这是,我们只想处理并生成一个'section'元素一次。 'section [position()> 1]'是与所有'section'元素匹配的另一个匹配模式,除了匹配前一个匹配模式的匹配模式外。匹配的模板没有主体,因此这些'section'元素根本不被处理。 – 2012-04-04 13:54:32

+0

感谢您的澄清 – 2012-04-04 14:44:20

1

这里是我的XSLT的1.0尝试:

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

    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="*"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:apply-templates/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="root"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:apply-templates select="*[name() != 'section']"/> 
     <xsl:element name="section"> 
     <xsl:apply-templates select="section"/> 
     </xsl:element> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="section"> 
    <xsl:apply-templates select="*"/> 
    </xsl:template> 

</xsl:stylesheet> 
+0

感谢@ hroptatyr它的工作原理 – 2012-04-04 10:34:36