XSLT:复制 XML 的节点并更改名称空间

XSLT: Copy a node of XML and change namespace

我需要复制 XML 的节点,删除所有前缀命名空间并更改命名空间,下面是 "orignal" XML 的示例和预期结果。

原文:

<service:Body xmlns:service="xxx.yyy.zzz" xmlns:schema="aaa.bbb.ccc">
  <schema:MAIN>
    <schema:Message>
      <schema:XXXXX0>
        <schema:XXXXX010>XXXXX0</schema:XXXXX010>
        <schema:XXXXX020>I</schema:XXXXX020>
        <schema:XXXXX030>8888</schema:XXXXX030>
        <schema:XXXXX040>08</schema:XXXXX040>
        <schema:XXXXX050>0002</schema:XXXXX050>
        <schema:XXXXX060>01</schema:XXXXX060>
        <schema:XXXXX090>00</schema:XXXXX090>
        <schema:XXXXX100>20190830122000</schema:XXXXX100>
        <schema:XXXXX110>1.0</schema:XXXXX110>
        <schema:XXXXX120>A</schema:XXXXX120>
        <schema:XXXXX130>AAA</schema:XXXXX130>
        <schema:XXXXX140>1</schema:XXXXX140>
        <schema:XXXXX150>PTT</schema:XXXXX150>
      </schema:XXXXX0>
    </schema:Message>
  </schema:MAIN>
</service:Body>

预期结果

<ns0:Message xmlns:ns0="hhh.kkk.yyy">
  <XXXXX0>
    <XXXXX010>XXXXX0</XXXXX010>
    <XXXXX020>I</XXXXX020>
    <XXXXX030>8888</XXXXX030>
    <XXXXX040>08</XXXXX040>
    <XXXXX050>0002</XXXXX050>
    <XXXXX060>01</XXXXX060>
    <XXXXX090>00</XXXXX090>
    <XXXXX100>20190830122000</XXXXX100>
    <XXXXX110>1.0</XXXXX110>
    <XXXXX120>A</XXXXX120>
    <XXXXX130>AAA</XXXXX130>
    <XXXXX140>1</XXXXX140>
    <XXXXX150>PTT</XXXXX150>
  </XXXXX0>
</ns0:Message>

您只能使用 XSLT-1.0 解决此问题。

使用以下样式表设置适当的命名空间,然后使用模板删除周围的 schema:Bodyschema:MAIN 元素。之后,它还会从 schema:Message 元素中删除命名空间,并使用新的目标命名空间 hhh.kkk.yyy 重新创建它。现在,使用修改后的 Identity 模板 可以轻松删除其余元素的剩余命名空间。 xsl:strip-space... 只是去掉了输出中一些不必要的空格。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:service="xxx.yyy.zzz" xmlns:schema="aaa.bbb.ccc" xmlns:ns0="hhh.kkk.yyy">
<xsl:strip-space elements="schema:MAIN" />

  <!-- Modified identity template --> 
  <xsl:template match="*">
      <xsl:element name="{local-name()}">
          <xsl:apply-templates select="node()|@*" />
      </xsl:element>
  </xsl:template>     

  <xsl:template match="service:Body | schema:MAIN">
      <xsl:apply-templates select="node()|@*" />
  </xsl:template>

  <xsl:template match="schema:Message">
      <xsl:element name="ns0:Message" namespace="hhh.kkk.yyy">
          <xsl:apply-templates select="node()|@*" />
      </xsl:element>
  </xsl:template>

</xsl:stylesheet>

它的输出是:

<ns0:Message xmlns:ns0="hhh.kkk.yyy">
  <XXXXX0>
    <XXXXX010>XXXXX0</XXXXX010>
    <XXXXX020>I</XXXXX020>
    <XXXXX030>8888</XXXXX030>
    <XXXXX040>08</XXXXX040>
    <XXXXX050>0002</XXXXX050>
    <XXXXX060>01</XXXXX060>
    <XXXXX090>00</XXXXX090>
    <XXXXX100>20190830122000</XXXXX100>
    <XXXXX110>1.0</XXXXX110>
    <XXXXX120>A</XXXXX120>
    <XXXXX130>AAA</XXXXX130>
    <XXXXX140>1</XXXXX140>
    <XXXXX150>PTT</XXXXX150>
  </XXXXX0>
</ns0:Message>