首页 > 解决方案 > 使用 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。

标签: xmlxslt

解决方案


与您之前的问题( 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>

推荐阅读