xml - 使用 XSLT 重构 XML 节点

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

谢谢

最佳答案

您可以生成如下元素:

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

相关文章:

c# - Xdocument - 如何转换非 html 安全字符

java - 基于XSD文件的JAXB java代码生成

templates - xsl :fo template match not firing on nested list

c# - 转换大型 Xml 文件

css - 如何在 xsl : when test= statement, 中调用特定的 CSS 类名以便测试证明是正确的?

xml - 有什么办法可以在 Linux 中将两个 xml 合并为一个 xml

Java 解析 XML 行的简单方法

java - 如何从生成的 JAXB 中删除命名空间

android - 通过 SOAP 发送 xml 数据时无法获得响应

xml - 我们可以使用 shell 脚本(或任何脚本/编程)在 Linux 上使用 XSLT 转换 XML 吗?