使用XSLT重构XML节点

时间:2010-06-06 20:28:45

标签: xml xslt

希望使用XSLT转换我的XML。示例XML如下:

<root>
<info>
    <firstname>Bob</firstname>
    <lastname>Joe</lastname>
</info>
<notes>
    <note>text1</note>
    <note>text2</note>
</notes>
<othernotes>
    <note>text3</note>
    <note>text4</note>
</othernotes>

我希望提取所有“note”元素,并将它们放在父节点“notes”下。

我正在寻找的结果如下:

<root>
<info>
    <firstname>Bob</firstname>
    <lastname>Joe</lastname>
</info>
<notes>
    <note>text1</note>
    <note>text2</note>
    <note>text3</note>
    <note>text4</note>
</notes>
</root>

我尝试使用的XSLT允许我提取所有“注释”,但是,我无法弄清楚如何将它们包装回“注释”节点中。

这是我正在使用的XSLT:

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

    <xsl:template match="notes|othernotes">
        <xsl:apply-templates select="note"/>
    </xsl:template>
    <xsl:template match="*">
    <xsl:copy><xsl:apply-templates/></xsl:copy>
    </xsl:template>

</xsl:stylesheet>

我在上面的XSLT中获得的结果是:

<root>
<info>
    <firstname>Bob</firstname>
    <lastname>Joe</lastname>
</info>
    <note>text1</note>
    <note>text2</note>
    <note>text3</note>
    <note>text4</note>
</root>

由于

2 个答案:

答案 0 :(得分:2)

您可以生成如下元素:

<xsl:element name="notes">
   <!-- inject content of notes element here using e.g. <xsl:copy> or <xsl:copy-of> -->
</xsl:element>

稍作修改,上述方法也适用于在特定XML命名空间中生成元素。 但是,由于您不希望在命名空间中生成元素,因此存在一个快捷方式:

<notes>
  <!-- inject content of notes element here using e.g. <xsl:copy> or <xsl:copy-of> -->
</notes>

在您的具体示例中,我将重构您的样式表以执行以下操作:

<xsl:template match="root">
   <root>
     <xsl:copy-of select="info"/>
     <notes>
        <xsl:copy-of select="*/note"/>
     </notes>
   </root>
</xsl:template>

答案 1 :(得分:1)

你会找到这样的东西: -

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

<xsl:template match="/root">
  <xsl:copy>
     <xsl:apply-templates select="@*|node()[local-name() != 'notes' and local-name() != 'othernotes']
  </xsl:copy>
  <notes>
     <xsl:apply-templates select="othernotes/note | notes/note" />
  </notes>
</xsl:template>

您可以控制根节点的结构。首先复制未命名为“notes”或“othernote”的根目录下的所有内容。然后直接创建一个“notes”元素,然后将所有“note”元素组合在“othernotes”或“notes”元素下。

相关问题