在我的XSL中添加了xmlns到我的XML中。將xmlns屬性添加到使用XSL的XML文檔的問題
<xsl:template match="root">
<xsl:element name="root" namespace="myXslLoc">
<xsl:attribute name="Name">Default</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
<xsl:template>
上面確實爲根元素(頂層元素)添加了xmlns屬性。但是它也爲後續元素添加了xmlns。這是事實:
<root Name="Default" xmlns="myXslLoc">
<steps xmlns=""> <-- where did this attribute come from?
.
.
.
</steps>
</root>
我不知道step元素中的xmlns來自哪裏。我沒有指定將xmlns添加到steps元素的代碼。下面是我的xsd snipet:
<xs:complexType name="root">
<xs:sequence>
<xs:element name="steps" type="steps" maxOccurs="1" MinOccurs="1"/>
</xs:sequence>
<xs:attribute name="Name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="steps">
<xs:sequence>
<xs:element name="step" type="step" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
在我的xsl或xsd中是否有問題?我似乎無法弄清楚問題來自哪裏。
謝謝。
編輯: 以下Dimitre的轉換代碼,我設法將名稱空間屬性插入根元素。然而,更多的名稱空間屬性實例出現在轉換後的xml文檔中。
下面是發生了什麼:
<root Name="Default" xmlns="myXslLoc">
<steps> <-- where did this attribute come from?
<step name="A">
.
</step>
.
.
<!-- the below is the final steps element -->
<step name="Z" xmlns=""> <-- this xmlns was unexpectedly added.
<steps xmlns="myXslLoc"> <-- this one as well.
.
.
.
</steps>
</step>
<step Name="Step manually added by identity transformation (addLastNode stuff)">
.
.
.
</step>
</steps>
</root>
的XSL看起來是這樣的:
<xsl:template match="root">
<xsl:element name="root namespace="myXslLoc">
<xsl:attribute name="Name">Default</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
<xsl:template>
<xsl:template match="*">
<xsl:element name="{name()}" namespace="{$addMyXslLoc}">
<xsl:copy-of select="namespace::*"/>
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
<xsl:template>
<xsl:param name="addMyXslLoc" select="'myXslLoc'"/>
<xsl:template match="/*/steps/step[position()=last()]">
<xsl:call-template name="identity"/>
<xsl:copy-of select="$addLastNodes"/>
</xsl:template>
<xsl:param name="addLastNodes">
<step Name="Total Cost">
<items>
<item name="A">
</item>
<item name="b">
</item>
</items>
</step>
</xsl:param>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
我喜歡怎樣的命名空間,現在的根元素上出現(連同名稱屬性)。但是我現在面臨的問題是無法擺脫插入到xml文檔的最後一個元素中的名稱空間,不包括通過轉換添加的名稱空間。編輯: 更新了addLastNodes xsl。
您的解決方案確實將名稱空間添加到根元素。然而,它還將名稱空間添加到根元素中的一個步驟和步驟元素中(我相信這是我上一篇文章中自定義插入步驟之前的最後一步)。有沒有什麼辦法解決這一問題? (另外,我已經在單獨的xsl:template中使用 blah xsl:attribute>向根元素添加了Name屬性)。謝謝。 –
BeraCim
2010-08-16 07:42:14
@BeraCim:是的。這解決了你所抱怨的問題:'xmlns =「」'的出現。你不是想讓這個消失嗎?如果不是,請編輯您的問題並說明模式的簡短實例 - 給出確切的XML,以及您希望從轉換中得到的確切輸出是什麼。 – 2010-08-16 12:33:50
@BeraCim:我看到你在答案中添加了一個XML文檔,但只有*部分* xslt代碼。特別是,我想查看'addLastNodes'參數的全部內容。它在那裏,需要改變。 – 2010-08-17 02:30:37