XSLT命名空间和解析硬编码前缀

时间:2012-12-06 15:22:07

标签: xslt namespaces xslt-1.0

对于Google Merchant Center集成,我需要提供XML,其中某些元素具有名称空间前缀,例如:

   <g:availability>in stock</g:availability>, 

虽然其他人不需要命名空间,例如:

   <title>My Product</title>

但是,我无法想出一个允许我的XSLT:

1)指定相应的命名空间(xmlns:g =“http://base.google.com/ns/1.0”) 和 2)前缀属性

,没有在某处添加“g”命名空间。


我相信

exclude-result-prefixes =“g”对我的用例不起作用。要重新迭代,我需要在一些XML元素前加上“g”。如果我不需要这样做,例如

<availability>in stock<availability> 

,然后排除结果前缀工作正常。但是,当我向我的元素添加前缀时,在XSLT运行时会添加名称空间。我在下面有一个这种情况的例子。

感谢。


XSLT:

    

<xsl:template match="/">

    <xsl:element name="type">
        <xsl:for-each select="categories/product">
            <xsl:element name="product">
                <g:availability>
                    <xsl:text>preorder</xsl:text>
                </g:availability>
            </xsl:element>
        </xsl:for-each>
    </xsl:element>
</xsl:template>


XML:

<?xml version="1.0" encoding="UTF-8"?>
<categories>
<product>
<id>1</id> 
<preorder>true</preorder>
<releaseDate>true</releaseDate>
<quantity>1</quantity>
</product>
<product>
<id>2</id> 
<preorder>false</preorder>
<quantity>0</quantity>
</product>
<product>
<id>3</id> 
<preorder></preorder>
<quantity>10</quantity>
</product>

输出:

<?xml version="1.0" encoding="UTF-8"?>
<type>
<product>
<g:availability xmlns:g="http://base.google.com/ns/1.0">preorder</g:availability>
</product>
<product>
<g:availability xmlns:g="http://base.google.com/ns/1.0">preorder</g:availability>
</product>
<product>
<g:availability xmlns:g="http://base.google.com/ns/1.0">preorder</g:availability>
</product>
</type>

(不完整)Google Merchant,预期的XML示例

<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title>Example - Online Store</title>
<item>
<title>LG Flatron M2262D 22" Full HD LCD TV</title>
<g:id>TV_123456</g:id>
<g:condition>used</g:condition>
</item>     
</channel>
</rss>

使用XSLT的第1版

1 个答案:

答案 0 :(得分:1)

您需要名称空间声明某处,因为没有它,XML不是名称空间良好的形式,但您可以使它在根元素上只出现一次而不是在每个{{1}上重复出现通过在样式表中声明名称空间并在模板中使用文字根元素而不是<g:availability>。例如,要生成类似于问题中提供的Google示例的内容,您可以说:

<xsl:element>

这应该产生

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
                xmlns:g="http://base.google.com/ns/1.0">

    <xsl:template match="/">
        <rss version="2.0">
            <channel>
                <title>Example - Online Store</title>
                <xsl:for-each select="categories/product">
                    <item>
                        <g:id><xsl:value-of select="id"/></g:id>
                        <g:availability>preorder</g:availability>
                    </item>
                </xsl:for-each>
             </channel>
        </rss>
    </xsl:template>
</xsl:stylesheet>

这样做的原因是因为文字结果元素将样式表中位置范围内的命名空间绑定带到结果树中。