2011-02-10 39 views
2

下面的xslt代碼不適用於下面的XML文件。但是,如果我從xml文件的「對象」節點中刪除命名空間屬性,它將按預期工作。我如何修復xslt代碼,以便在根節點中具有名稱空間屬性時它能夠正常工作?首先發布,抱歉如果格式化搞砸了。由於在根節點中聲明名稱空間時xslt腳本不起作用

XML文件:

<objects xmlns="http://www.spicefactory.org/parsley" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > 
<object id="models" type="blah"> 

</object> 
</objects> 

XSLT代碼:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > 
<xsl:output method="xml" indent="no"/> 

<xsl:template match="node()|@*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
</xsl:template> 
<xsl:template match="object"> 
    <object new_attr="attr value "> 
    <xsl:apply-templates select="node()|@*"/> 
    </object> 
</xsl:template> 
</xsl:stylesheet> 
+0

可能重複具有默認命名空間設置爲xmlns的XML源代碼](http://stackoverflow.com/questions/1344158/xslt-with-xml-source-that-has-a-default-namespac e-set-to-xmlns) – 2011-02-12 15:35:09

回答

10

您需要申報,並在XSLT使用相同的XML命名空間:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:sfp="http://www.spicefactory.org/parsley"> 

<xsl:output method="xml" indent="no"/> 

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

<xsl:template match="sfp:object"> 
    <sfp:object new_attr="attr value "> 
    <xsl:apply-templates select="node()|@*"/> 
    </sfp:object> 
</xsl:template> 
</xsl:stylesheet> 
[XSLT與
+0

非常感謝Phillip,它幫助我縮小了範圍。它與我的xml中的默認命名空間有關。如果默認名稱空間位於xml中,則我的xslt轉換不起作用。如果默認名稱空間從我的xml中被刪除,則xslt轉換將起作用。所以,我可以讓我的變換工作,並保持默認名稱空間在XML?謝謝。 – dt1000 2011-02-11 02:44:32

相關問題