首页 > 解决方案 > 如何创建通用 XSLT 以添加节点

问题描述

我有多个各种格式的 XML 文件,所有这些文件在通过之前都需要有一个特定的标签,因此我想编写一个通用的 XSLT,它将接受任何 XML 输入,并在有效负载之前和之后简单地添加额外的标签. 例如:

输入 XML(示例 1)

<?xml version="1.0" encoding="UTF-8"?>

<Order>
    <data1>
        <test>1</test>
        <test2>2</test2>
        <test3>3</test3>
    </data1>
</Order>

它也可以是另一个 XML<Invoice>或其他任何东西。

所需输出

<?xml version="1.0" encoding="UTF-8"?>
<soap:envelope>
<soap:body>
<Order>
    <data1>
        <test>1</test>
        <test2>2</test2>
        <test3>3</test3>
    </data1>
</Order>
</soap:body>
</soap:envelope>

使用以下 XSLT,我需要知道哪个节点进入(订单或发票)以匹配模式 - 但这可以是通用的吗?

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
<!-- I do not want to specify the node here -->
    <xsl:template match="Order">
        <soap:envelope>
        <soap:body>
            <xsl:copy-of select="*"/>              
        </soap:body>
        </soap:envelope>
    </xsl:template>
  </xsl:stylesheet>

标签: templatesgenericsselectxsltnodes

解决方案


您显示的输出不是格式良好的 XML 文档:如果不将前缀绑定到命名空间,您将无法使用它。您的 XSLT 有同样的缺陷,并且不能在不产生错误的情况下使用(至少不能使用符合标准的处理器)。

我猜你想使用:

XSLT 1.0

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

<xsl:template match="/">
    <soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
        <soap:body>
            <xsl:copy-of select="."/>              
        </soap:body>
    </soap:envelope>
</xsl:template>

</xsl:stylesheet>

生成有效的SOAP消息:

<?xml version="1.0" encoding="UTF-8"?>
<soap:envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
   <soap:body>
      <Order>
         <data1>
            <test>1</test>
            <test2>2</test2>
            <test3>3</test3>
         </data1>
      </Order>
   </soap:body>
</soap:envelope>

推荐阅读