如何创建通用 XSLT 以添加节点

How to create a generic XSLT to add nodes

我有多个 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>

为此您需要匹配 root

<xsl:template match="/">
    <soap:envelope>
    <soap:body>
        <xsl:copy-of select="."/>              
    </soap:body>
    </soap:envelope>
</xsl:template>

测试:https://xsltfiddle.liberty-development.net/jxWZS7L

您显示的输出不是格式正确的 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>