templates - 如何创建通用 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>
解决方案
您显示的输出不是格式良好的 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>
推荐阅读
- visual-studio - visual stdio 2019 无法识别 net 5.0 框架
- android - 如何从可组合函数中获取当前活动?
- kubernetes - 如何在 Helm 中的其他 pod 之前先安装 istio mutating webhook 和 istiod?
- ant-media-server - 启用 ABR 后,我们如何在 Ant Media 服务器中自定义 MP4 节省?
- java - 休息呼叫中的 TimeoutException
- git - 合并来自同一 git 存储库的两个文件的历史记录
- mongodb - 数组字段上的索引无效
- reactjs - React useEffect Typescript问题:多种返回类型
- google-cloud-platform - 有没有办法在列出 GCP 实例时区分 GCE 实例和 GKE 实例
- python - 从python的元组列表中提取值