使用xsl更改子元素的命名空间

时间:2017-02-06 10:55:30

标签: xslt

如何替换xml中子元素的命名空间? 例如,我有这个源文件:

<ns:Parent xmlns:ns="http://test.com">
  <ns:Name>John</ns:Name>
  <ns:Country>Japan</ns:Country>
  <ns:Contact>9999999</ns:Contact>
</ns:Parent>

我的输出应该是这样的:

<ns:Parent xmlns:ns="http://test.com">
  <ns1:Name xmlns:ns1="http://development.com">John</ns1:Name>
  <ns:Country>Japan</ns:Country>
  <ns:Contact>9999999</ns:Contact>
</ns:Parent>

所以基本上除了Name之外的所有其他字段都没有受到影响。

1 个答案:

答案 0 :(得分:1)

首先从identity template开始,处理复制您不想更改的所有节点

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

然后,只需添加一个模板以匹配ns:Name,您可以在所需的命名空间中创建一个新节点(ns1元素上定义了xsl:stylesheet

<xsl:template match="ns:Name">
    <ns1:Name>
        <xsl:apply-templates select="@*|node()"/>
    </ns1:Name>
</xsl:template>

试试这个XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
                xmlns:ns="http://test.com"
                xmlns:ns1="http://development.com">
    <xsl:output method="xml" indent="yes" />

    <xsl:template match="ns:Name">
        <ns1:Name>
            <xsl:apply-templates select="@*|node()"/>
        </ns1:Name>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
相关问题