2010-12-09 25 views
2

我想更改xml的命名空間url值。我有一個像下面這樣的xml如何更改根節點的屬性值和命名空間url

<catalog xmlns="http://someurl" 
     xmlns:some="http://someurl2" 
     xsi:schemaLocation="http://someurl some.3.0.xsd" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <cd> 
     <title>Empire Burlesque</title> 
     <artist>Bob Dylan</artist> 
     <country>USA</country> 
     <company> 
      <name>Columbia</name> 
     </company> 
     <price>10.90</price> 
     <year>1985</year> 
    </cd> 
</catalog> 

我正在使用標識轉換。有什麼辦法可以改變命名空間ursl中的文本嗎?例如,我想將網址http:// someurl改爲http:// someur2' 和'http:// someurl some.3.0.xsd'改爲'http:// someurl some.4.0.xsd'

+0

想必你想改變每個元素的命名空間,對吧? (這將會改變根元素上默認名稱空間聲明的效果。) – LarsH 2010-12-09 15:38:50

+0

@ user527650:輸入源中缺少模式實例名稱空間聲明。 – 2010-12-09 15:40:40

回答

9

這應做到:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" 
    xmlns:old="http://someurl" exclude-result-prefixes="old"> 
    <!-- Identity transform --> 
    <xsl:template match="@* | node()"> 
     <xsl:copy> 
     <xsl:apply-templates select="@* | node()"/> 
     </xsl:copy> 
    </xsl:template> 

    <!-- replace namespace of elements in old namespace --> 
    <xsl:template match="old:*"> 
     <xsl:element name="{local-name()}" namespace="http://someurl2"> 
     <xsl:apply-templates select="@* | node()"/> 
     </xsl:element> 
    </xsl:template> 

    <!-- replace xsi:schemaLocation attribute --> 
    <xsl:template match="@xsi:schemaLocation"> 
     <xsl:attribute name="xsi:schemaLocation">http://someurl some.4.0.xsd</xsl:attribute> 
    </xsl:template> 
</xsl:stylesheet> 

與樣品輸入,這給:

<?xml version="1.0" encoding="utf-8"?> 
<catalog xmlns="http://someurl2" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://someurl some.4.0.xsd"> 
    <cd> 
     <title>Empire Burlesque</title> 
     <artist>Bob Dylan</artist> 
     <country>USA</country> 
     <company> 
     <name>Columbia</name> 
     </company> 
     <price>10.90</price> 
     <year>1985</year> 
    </cd> 
</catalog> 

說明:

最後兩個templat es被添加到身份轉換中,因此更具體,因此採用比身份模板更高的默認優先級。它們分別覆蓋「舊」命名空間中的元素和xsl:schemaLocation屬性的標識模板。

爲「老:*」模板輸出具有相同的本地名稱作爲一個要替換(即,沒有命名空間中的名稱)的元素,並賦予它新的期望的命名空間。令人高興的是,XSLT處理器(或者更恰當的說,序列化程序;我爲我的測試使用了Saxon 6.5.5)決定將這個新的名稱空間設置爲默認名稱空間,因此它爲其輸出添加了一個默認名稱空間聲明根元素。我們沒有要求它這樣做,理論上這個新的命名空間是默認還是使用前綴應該沒有關係。但你似乎希望它成爲默認設置,這樣可以很好地解決問題。

相關問題