如何使用xslt 2.0替换名称空间uri前缀和根元素

时间:2019-03-01 13:56:49

标签: xslt xslt-2.0

我有一个XML文件,其中包含用命名空间前缀和相应的uri限定的元素。

我想做两件事:

  1. 在整个xml中用不同的名称空间替换名称空间uri和前缀: xmlns:urn =“ http:// abcd”到xmlns:xsns =“ http:// 123” 这样<urn:FirstELement>就变成了<xsns:SecondElement>

  2. 根元素需要替换: <urn:RootElementOld xmlns:urn="http://abcd">替换为<xsns:RootElementNew xmlns:xsns="http://123">

输入XML(类似于实际):

    <urn:RootElementOld xmlns:urn="http://abcd">
    <urn:FirstElement>
        <urn:FirstSubElement id1="abc" id2="efg">FirstValue</urn:FirstSubElement>
        <urn:SecondSubElement id3="hij" id4="klm">SecondValue</urn:SecondSubElement>
    </urn:FirstElement>
    <urn:SecondElement>
        <urn:ThirdSubElement id5="nop" id6="qrs">ThirdValue</urn:ThirdSubElement>
        <urn:FourthSubElement id7="tuv" id8="wxy">FourthValue</urn:FourthSubElement>
    </urn:SecondElement>
</urn:RootElementOld>

预期的输出XML:

    <xsns:RootElementNew xmlns:xsns="http://123">
    <xsns:FirstElement>
        <xsns:FirstSubElement id1="abc" id2="efg">FirstValue</xsns:FirstSubElement>
        <xsns:SecondSubElement id3="hij" id4="klm">SecondValue</xsns:SecondSubElement>
    </xsns:FirstElement>
    <xsns:SecondElement>
        <xsns:ThirdSubElement id5="nop" id6="qrs">ThirdValue</xsns:ThirdSubElement>
        <xsns:FourthSubElement id7="tuv" id8="wxy">FourthValue</xsns:FourthSubElement>
    </xsns:SecondElement>
</xsns:RootElementNew>

我的输出:

    <xsns:RootElementOld xmlns:xsns="http://123">
    <xsns:FirstElement>
        <xsns:FirstSubElement id1="abc" id2="efg">FirstValue</xsns:FirstSubElement>
        <xsns:SecondSubElement id3="hij" id4="klm">SecondValue</xsns:SecondSubElement>
    </xsns:FirstElement>
    <xsns:SecondElement>
        <xsns:ThirdSubElement id5="nop" id6="qrs">ThirdValue</xsns:ThirdSubElement>
        <xsns:FourthSubElement id7="tuv" id8="wxy">FourthValue</xsns:FourthSubElement>
    </xsns:SecondElement>
</xsns:RootElementOld>

我的XSLT:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:urn="http://abcd"
    xmlns:xsns="http://123" exclude-result-prefixes="urn">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="*">
        <xsl:element name="xsns:{local-name(.)}" namespace="http://123">
            <xsl:apply-templates select="@* | node()" />
        </xsl:element>
    </xsl:template>

    <xsl:template match="@*">
        <xsl:attribute name="{local-name(.)}"> 
        <xsl:value-of select="." /> 
        </xsl:attribute>
    </xsl:template>

    <xsl:template match="urn:RootElementOld">
        <xsl:element name="xsns:RootElementNew" namespace="http://123">
            <xsl:apply-templates select="@* | node()" />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

能请你帮我吗?我是XSLT的新手。

0 个答案:

没有答案