如何使用XSLT将名称空间添加到XML的根元素?

如何使用XSLT将名称空间添加到XML的根元素?,xml,xslt,xml-parsing,Xml,Xslt,Xml Parsing,我有一个输入XML <Request> <Info> <Country>US</Country> <Part>A</Part> </Info> </Request> 美国 A. 我的输出应该是 <Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http

我有一个输入XML

<Request>
  <Info>
    <Country>US</Country>
    <Part>A</Part>
   </Info>
</Request>

美国
A.
我的输出应该是

<Request
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="http://hgkl.kj.com">
  <Info>
    <Country>US</Country>
    <Part>A</Part>
  </Info>
</Request>

美国
A.

请让我知道如何添加多个名称空间和一个类似上述XML的默认名称空间。

以下是我在XSLT 2.0中的做法

XML输入

<Request>
    <Info>
        <Country>US</Country>
        <Part>A</Part>
    </Info>
</Request>
<Request xmlns="http://hgkl.kj.com"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Info>
      <Country>US</Country>
      <Part>A</Part>
   </Info>
</Request>

美国
A.
XSLT2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="*" priority="1">
        <xsl:element name="{local-name()}" namespace="http://hgkl.kj.com">
            <xsl:namespace name="xsi" select="'http://www.w3.org/2001/XMLSchema-instance'"/>
            <xsl:namespace name="xsd" select="'http://www.w3.org/2001/XMLSchema'"/>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

XML输出

<Request>
    <Info>
        <Country>US</Country>
        <Part>A</Part>
    </Info>
</Request>
<Request xmlns="http://hgkl.kj.com"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Info>
      <Country>US</Country>
      <Part>A</Part>
   </Info>
</Request>

美国
A.

这里有一个XSLT1.0选项,它生成相同的输出,但要求您知道根元素的名称

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="/Request">
        <Request xmlns="http://hgkl.kj.com" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <xsl:apply-templates select="@*|node()"/>           
        </Request>
    </xsl:template>

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

</xsl:stylesheet>