2013-07-01 14 views
-1

我有以下XML:一對一XSLT地圖命名空間操作

<ns0:Root xmlns:ns0="http://root" xmlns:nm="http://notroot"> 
    <nm:MSH> 
    <content>bla</content> 
    </nm:MSH> 
    <ns0:Second> 
    <ns0:item>aaa</ns0:item> 
    </ns0:Second> 
    <ns0:Third> 
    <ns0:itemb>vv</ns0:itemb> 
    </ns0:Third> 
</ns0:Root> 

這是我期望的結果:

<Root xmlns="http://root" xmlns:nm="http://notroot"> 
    <nm:MSH> 
    <content>bla</content> 
    </nm:MSH> 
    <Second> 
    <item>aaa</item> 
    </Second> 
    <Third> 
    <itemb>vv</itemb> 
    </Third> 
</Root> 

我需要編寫一個XSLT 1.0執行該地圖。

我真的沒有線索怎麼做,因此它看起來很簡單。

任何人都可以請幫忙嗎?

回答

1

的元素從xmlns:ns0="http://root"命名空間移動到默認的命名空間。 用途:

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

爲了使http://root默認命名空間添加xmlns="http://root"樣式表聲明。

因此,你可以嘗試這樣的事:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" 
    xmlns:ns0="http://root" 
    xmlns="http://root" 
    exclude-result-prefixes="ns0" > 
    <!-- Identity transform (e.g. http://en.wikipedia.org/wiki/Identity_transform#Using_XSLT --> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()" /> 
     </xsl:copy> 
    </xsl:template> 

    <!-- match root element and fore notroot namespace to this --> 
    <xsl:template match="/*"> 
     <Root xmlns:nm="http://notroot"> 
      <xsl:apply-templates select="@*|node()" /> 
     </Root> 
    </xsl:template> 


    <xsl:template match="content"> 
     <content> 
      <xsl:apply-templates select="@*|node()" /> 
     </content> 
    </xsl:template> 
    <!-- move attributes with prefix ns0 to default namespace --> 
    <xsl:template match="@ns0:*"> 
     <xsl:attribute name="newns:{local-name()}"> 
      <xsl:value-of select="."/> 
     </xsl:attribute> 
    </xsl:template> 

    <!-- move elements with prefix ns0 to default namespace --> 
    <xsl:template match="ns0:*"> 
     <xsl:element name="{local-name()}"> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:element> 
    </xsl:template> 

</xsl:stylesheet> 
+0

+1。最後,添加'exclude-result-prefixes =「ns0」'來排除輸出'Root'元素上多餘的'xmlns:ns0'聲明。 –

+0

謝謝!有用!你能解釋一下每個模板在做什麼嗎? – ohadinho

+1

@ohadinho:我添加一些評論。 –

0

您的輸入和輸出之間的唯一區別是,內部nm:MSH所述content元件已經從沒有命名空間是在http://root命名空間移動。這可以由身份轉變與調整處理:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" 
     xmlns:ns0="http://root"> 

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

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

</xsl:stylesheet>