Xslt将元素复制到重命名的元素中

时间:2015-08-05 10:30:00

标签: xml xslt

我努力让我的Xslt产生我以后的东西。

我有以下xml

<data>
    <things>
        <name>A</name>
    </things>
    <other>
        <type>B</type>
    </other>
</data>

我希望我的输出xml是

<data>
    <stuff>
        <name>A</name>
        <type>B</type>
    </stuff>    
</data>

到目前为止,我有以下xslt,但这并不能完全产生我之后的

<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()|@*" name="identity">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

  <xsl:template match="data/things">
    <xsl:element name="stuff">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="data/other">
    <xsl:element name="stuff">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

这可能很简单,所以任何帮助都会受到赞赏

2 个答案:

答案 0 :(得分:0)

嗯,你的模型可能有点太多简单,但我建议如下:

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

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

    <xsl:template match="data">
        <xsl:copy>
            <stuff>
                <xsl:apply-templates/>
            </stuff>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="name|type">
        <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>

基本上,&#34;数据&#34;的模板放入自己的标签,将所有内容包含在&#34; stuff&#34;中。 &#34; name&#34;的模板和&#34;键入&#34;只需复制当前上下文节点。就是这样。

答案 1 :(得分:0)

  

这可能很简单

嗯,可能是:

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

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

<xsl:template match="/data">
    <xsl:copy>
        <stuff>
            <xsl:apply-templates select="*/*"/>
        </stuff>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

或者,如果您想要明确,请制作第二个模板:

<xsl:template match="/data">
    <xsl:copy>
        <stuff>
            <xsl:apply-templates select="things/name | other/type"/>
        </stuff>
    </xsl:copy>
</xsl:template>