2010-07-26 59 views
1

我有一個特定的問題,從某些定義了名稱空間前綴的XML中獲取寬度和高度的值。我可以很容易地使用普通的xpath與命名空間「n:」獲得其他值,例如來自RelatedMaterial的SomeText,但無法獲取寬度和高度的值。XSLT從具有名稱空間前綴的標記中獲取值的問題

示例XML:

<Description> 
<Information> 
<GroupInformation xml:lang="en"> 
<BasicDescription> 
    <RelatedMaterial> 
    <SomeText>Hello</SomeText> 
    <t:ContentProperties> 
    <t:ContentAttributes> 
    <t:Width>555</t:Width> 
    <t:Height>444</t:Height> 
    </t:ContentAttributes> 
    </t:ContentProperties> 
    </RelatedMaterial> 
</BasicDescription> 
</GroupInformation> 
</Information> 
</Description> 

下面是從XSLT的提取物:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:n="urn:t:myfoo:2010" xmlns:tva2="urn:t:myfoo:extended:2008" 

<xsl:apply-templates select="n:Description/n:Information/n:GroupInformation"/> 

<xsl:template match="n:GroupInformation"> 
    <width> 
    <xsl:value-of select="n:BasicDescription/n:RelatedMaterial/t:ContentProperties/t:ContentAttributes/t:Width"/> 
    </width> 
</xsl:template> 

上面XSLT不用於獲取寬度工作。有任何想法嗎?

+2

您輸入的文件是無效的XML。前綴't'沒有被定義。你能澄清一下嗎? – 2010-07-26 12:29:25

回答

2

我不確定你已經意識到你的輸入和XSLT都是無效的,所以最好提供一些工作示例。

無論如何,如果我們看看XPath表達式n:BasicDescription/n:RelatedMaterial/t:ContentProperties/t:ContentAttributes/t:Width,那麼您使用的前綴n映射到urn:t:myfoo:2010,但是當數據infact位於默認名稱空間中時。前綴t也是如此,在輸入數據和XSLT中都沒有定義。

您需要在「雙方」,XML數據和XSLT轉換中定義名稱空間,它們需要是相同的,而不是前綴,而是URI。

其他人可能可以解釋這一點比我更好。

我已更正您的示例並添加了一些使此項工作的內容。

輸入:

<?xml version="1.0" encoding="UTF-8"?> 
<Description 
    xmlns="urn:t:myfoo:2010" 
    xmlns:t="something..."> 
    <Information> 
    <GroupInformation xml:lang="en"> 
     <BasicDescription> 
     <RelatedMaterial> 
      <SomeText>Hello</SomeText> 
      <t:ContentProperties> 
      <t:ContentAttributes> 
       <t:Width>555</t:Width> 
       <t:Height>444</t:Height> 
      </t:ContentAttributes> 
      </t:ContentProperties> 
     </RelatedMaterial> 
     </BasicDescription> 
    </GroupInformation> 
    </Information> 
</Description> 

XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" 
    xmlns:n="urn:t:myfoo:2010" 
    xmlns:t="something..."> 

    <xsl:template match="/"> 
    <xsl:apply-templates select="n:Description/n:Information/n:GroupInformation"/> 
    </xsl:template> 

    <xsl:template match="n:GroupInformation"> 
    <xsl:element name="width"> 
     <xsl:value-of select="n:BasicDescription/n:RelatedMaterial/t:ContentProperties/t:ContentAttributes/t:Width"/> 
    </xsl:element> 
    </xsl:template> 

</xsl:stylesheet> 

輸出:

<?xml version="1.0" encoding="UTF-8"?> 
<width>555</width> 
相關問題