xml - 使用 XSL 在特定位置添加特定元素
问题描述
我有这个xml。
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Messages xmlns:ns0="http://sap.com/xi/XI/SplitAndMerge">
<ns0:Message1>
<ns:sap_order_status xmlns:ns="http://orders.com">
<row>
<message_name/>
<message_num/>
<order_id/>
</row>
</ns:sap_order_status>
</ns0:Message1>
</ns0:Messages>
我需要我的 xml 在第一个之后有第二个 sap_order_status 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Messages xmlns:ns0="http://sap.com/xi/XI/SplitAndMerge">
<ns0:Message1>
<ns:sap_order_status xmlns:ns="http://orders.com">
**<sap_order_status>**
<row>
<message_name/>
<message_num/>
<order_id/>
</row>
**</sap_order_status>**
</ns:sap_order_status>
</ns0:Message1>
</ns0:Messages>
我过去曾为以前的消息获得过帮助,但这一条是如此不同,以至于我无法调整 XSL。
解决方案
与您之前的问题( Remove prefix from element )的唯一真正区别是您不再处理根元素,而是处理后代。
您只需要了解身份模板,它将在现有元素到达您需要修改的元素之前处理复制。
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
然后,不是让模板与根元素匹配,而是有一个模板与您希望将新子节点附加到的节点匹配:
<xsl:template match="ns:sap_order_status">
<xsl:copy>
<xsl:element name="{local-name()}">
<xsl:apply-templates />
</xsl:element>
</xsl:copy>
</xsl:template>
ns:
前缀将在元素xsl:stylesheet
上声明。
试试这个 XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:ns="http://orders.com">
<xsl:output method="xml" indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="ns:sap_order_status">
<xsl:copy>
<xsl:element name="{local-name()}">
<xsl:apply-templates />
</xsl:element>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- php - php laravel 中的数组有问题
- android-ndk - Android ndk 构建 32Bits 共享库
- android - Flutter - 自动滚动到特定卡片
- swift - SwiftUI - macOS Big Sur - 如何将 ToolbarItem 移动到相应的右视图
- java - 如何在 Scala 中创建由 Set 支持的地图?
- python-3.x - 当我在 cx_freeze 'TypeError: expected str, bytes or os.PathLike object, not NoneType' 上运行 setup.py 时出现错误
- c - 当我不使用 scanf 时,我一定要使用“putch”功能吗?
- php - 我的程序需要填写所有标准,而不是选择用户想要多少标准
- oracle - oracle 中的 XMLType 不会为具有 Null 值的列生成标签
- python - python爬取以提取评论计数