我正在編寫一個XSLT轉換,我希望在根元素上定義所有名稱空間前綴。默認情況下,MS似乎在XML層次結構的第一個元素上創建一個新的前綴定義來使用該模式;這意味着如果這些元素與同一模式的共享祖先不相關,則可以在多個元素上引用相同的模式。將名稱空間添加到根元素
通過與期望的編碼根元素本身,所有作品:
<!-- ... -->
<ns0:root xmlns:ns0="http://some/schema" xmlns:ns1 = "http://another/schema">
<!-- rest of XSLT; including calls to other templates -->
</ns0:root>
<!-- ... -->
但是我無法找到任何方式使用xsl:element
實現代碼;例如
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="http://some/schema"
xmlns:ns1 = "http://another/schema"
>
<!-- ... -->
<xsl:element name="ns0:root">
<xsl:attribute name="ns1" namespace="http://www.w3.org/2000/xslns/">http://another/schema</xsl:attribute>
<!-- rest of XSLT; including calls to other templates -->
</xsl:element>
<!-- ... -->
是否有可能宣佈針對xls:element
命名空間前綴比元素本身以外的模式?
全部實施例
XML
<Demo xmlns="http://some/schema">
<a>Hello</a>
<b>World</b>
</Demo>
XSLT
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="http://some/schema"
xmlns:ns1 = "http://another/schema"
exclude-result-prefixes="xsl"
>
<xsl:output method="xml" indent="yes" version="1.0"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<xsl:element name="{name(.)}" namespace="{namespace-uri(.)}">
<xsl:apply-templates select="@* | node()" />
</xsl:element>
</xsl:template>
<xsl:template match="/ns0:Demo/ns0:a">
<xsl:element name="ns1:z">
<xsl:value-of select="./text()" />
</xsl:element>
</xsl:template>
<xsl:template match="/ns0:Demo/ns0:b">
<xsl:element name="ns1:y">
<xsl:value-of select="./text()" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
結果
<Demo xmlns="http://some/schema">
<ns1:z xmlns:ns1="http://another/schema">Hello</ns1:z>
<ns1:y xmlns:ns1="http://another/schema">World</ns1:y>
</Demo>
所需的結果
<Demo xmlns="http://some/schema" xmlns:ns1="http://another/schema">
<ns1:z>Hello</ns1:z>
<ns1:y>World</ns1:y>
</Demo>
或
<ns0:Demo xmlns:ns0="http://some/schema" xmlns:ns1="http://another/schema">
<ns1:z>Hello</ns1:z>
<ns1:y>World</ns1:y>
</ns0:Demo>
您可能想向我們展示最少但完整的XML輸入示例,您擁有的XSLT代碼,您需要的結果以及您獲得的結果,以便我們重現和理解問題。你使用'>'的代碼片段似乎並不是必須的,因爲你在運行時不計算元素名稱,所以我不確定爲什麼你需要'xsl:元素「。如果你想讓名稱空間聲明在所有模板中的所有結果元素的範圍內,那麼你可以將它們放在'xsl:stylesheet'上,但是看起來你已經有了。 –
無後顧之憂;請參閱更新版本的「完整示例」部分。 – JohnLBevan
你爲什麼在意?您呈現的期望和實際結果具有相同的語義。 –