2010-07-26 61 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> 
相关问题