2013-04-12 86 views
4

我有一個輸入XML如何使用XSLT將命名空間添加到我的XML的根元素?

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

我的輸出應該像

<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> 

請讓我知道如何添加多個命名空間和默認命名空間像上面的XML。

回答

16

這是我怎麼會做它在XSLT 2.0 ...

XML輸入

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

XSLT 2.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 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> 

下面是一個XSLT 1.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> 
+0

感謝ü非常@Daniel據工作... – Ironman

相關問題