繁体   English   中英

如何在xsl:template中分配名称空间

[英]How to assign namespace in xsl:template

对于xsl:template和名称空间的第100个问题,我深表歉意。 我确实读过其他问题(例如, 此处此处此处 ),但仍然无法将各个部分放在一起。

这是我的输入:

<?xml version="1.0" encoding="UTF-8" ?>
<AuthorIT version="6.2.0" xmlns="http://www.authorit.com/xml/authorit"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.authorit.com/xml/authorit AuthorIT.xsd">
    <Objects>
        <Book>
            <Object>
                <Description>1089-802-01</Description>
            </Object>
        </Book>
    </Objects>
</AuthorIT>

这是我的样式表:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ait="http://www.authorit.com/xml/authorit" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.authorit.com/xml/authorit AuthorIT.xsd">
<xsl:template match="/">
    <Table>
        <apply-templates/>
    </Table>
</xsl:template>
<xsl:template match="ait:Book">
    <Row>
        <Cell>
            <Data><xsl:value-of select="./Object/Description"/></Data>
        </Cell>
    </Row>
</xsl:template>

预期结果:

<Table>
    <Row>
        <Cell>
            <Data>1089-802-01</Data>
        </Cell>
    </Row>
</Table>

实际结果:

<Table>
       1089-802-01
</Table>

换句话说,xsl:template match =“ /”匹配,但xsl:template match =“ ait:Book”不匹配。

如何匹配Book元素?

请注意,我从输入根元素AuthorIT xmlns =“ http://www.authorit.com/xml/authorit”中获取了默认名称空间,并将其作为xmlns:ait =“ http://www.authorit添加到样式表中。 com / xml / authorit” 然后,我尝试将Book元素匹配为ait:Book 但是我一定对这个答案有误解。

我不知道它是否重要,但是我正在使用Saxon HE 9和Notepad ++ XML插件。

好吧<apply-templates/>是一个文字结果元素,您将需要<xsl:apply-templates/> 但是我没有得到结果( http://xsltransform.net/ej9EGcB ),你说得到了,我得到了

<?xml version="1.0" encoding="UTF-8"?><Table xmlns:ait="http://www.authorit.com/xml/authorit" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><apply-templates/></Table>

这清楚表明,您只需使用apply-templates子元素创建一个Table元素。

正如Martin Honnen所指出的那样,使用您的代码收到的实际结果并非您所声称的。

无论如何,要获得预期的结果,您必须进行更改

<xsl:value-of select="./Object/Description"/> 

至:

<xsl:value-of select="./ait:Object/ait:Description"/>

因为这些元素也在给定的命名空间中。

您还应该添加exclude-result-prefixes="ait"作为xsl:stylesheet元素的属性,并在那里删除多余的名称空间声明。

这是对<apply-templates/><xsl:apply-templates/>问题的补充。

当然,您需要关闭</xsl:stylesheet>标记。

谢谢大家的回答。

我做了以下事情:

  • 在样式表标签中添加了xmlns:ait="http://www.authorit.com/xml/authorit"声明。
  • 在相关位置添加了ait:前缀。
  • 在样式表标签中添加了exclude-result-prefixes="ait"

现在可以使用,尽管我不明白exclude-result-prefixes="ait"作用:使用和不使用转换都可以顺利进行。 也许是未来研究的话题。

<apply-templates/><xsl:apply-templates/>问题以及</xsl:stylesheet>标记是在简化帖子文件时出现的错别字。 对不起,感谢您指出。

特别感谢Martin Honnen提供的指向http://xsltransform.net的链接:我不知道它的存在并且非常方便。

尝试使用

<xsl:apply-templates/>

(您缺少“ xsl:”),并且

<xsl:template match="AuthorIT/Object/Books">

而不是“ ait:Book”。 这应该可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM