希望使用 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>
谢谢
最佳答案
您可以生成如下元素:
<xsl:element name="notes">
<!-- inject content of notes element here using e.g. <xsl:copy> or <xsl:copy-of> -->
</xsl:element>
稍加修改,上述方法也适用于在特定 XML 命名空间中生成元素。 然而,由于您不希望在 namespace 中生成元素,因此存在一个快捷方式:
<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>
关于xml - 使用 XSLT 重构 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2985791/