我将尝试解释XSLT如何处理命名空间前缀,并提供以下示例:XML:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:zno="http://feed.zinio.com/atom"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/2005/Atom
http://www.w3.org/1999/xhtml
http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd
http://feed.zinio.com/atom" >
<entry>
<author>
<name>By Sheila F. Buckmaster</name>
</author>
<category xml:lang="en" term="TRAVEL"/>
<content>
<h2 class="hl2">One of the world’s most entrancing cities becomes even more captivating when costumed revelers fill its tiny streets and grand piazzas during Carnevale. It is here that a star of the silent screen comes alive, antics and all</h2>
<div class="byline">By Sheila F. Buckmaster</div>
</content>
</entry>
</feed>
XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xslt:stylesheet version="1.0" xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:user="urn:my-scripts"
xmlns:x="http://www.w3.org/1999/xhtml"
xmlns:AP="http://www.w3.org/2005/Atom"
exclude-result-prefixes="xslt msxsl user">
<xslt:output method="xml" indent="yes"/>
<xslt:template match="/">
<xslt:apply-templates select="/AP:feed//AP:entry"/>
</xslt:template>
<xslt:template match="AP:entry">
<xslt:text>Hello from entry</xslt:text>
<xslt:apply-templates select="AP:content"/>
</xslt:template>
<xslt:template match="AP:content">
<xslt:text>Hello from content</xslt:text>
<xslt:apply-templates select="x:div[@class='byline']"/>
</xslt:template>
<xslt:template match="x:div[@class='byline']">
<xslt:copy-of select="."/>
</xslt:template>
</xslt:stylesheet>
我想要做的是访问我的“div”。由于我明确指定了命名空间,因此“Entry”和“Content”模板可以正常工作。但是当我尝试使用XHTML前缀(在我的情况下为“x”)访问“div”时,XSLT无法看到它。只有当我在“div”元素前加上“AP”命名空间前缀时,它才能正常工作:
<xslt:template match="AP:content">
<xslt:text>Hello from content</xslt:text>
<xslt:apply-templates select="AP:div[@class='byline']"/>
</xslt:template>
<xslt:template match="AP:div[@class='byline']">
<xslt:copy-of select="."/>
</xslt:template>
但是我觉得这不对,因为DIV元素应该在XHTML命名空间中。我做错了什么?
@class
。显然,您可以根据自己的输出需求进行修改。希望您理解它为什么会出现这种行为以及如何控制它。 - Mads Hansen<x:div>
,你可以将元素@name更改为name="x:{local-name()}"
。 - Mads Hansen<div xmlns="http://www.w3.org/1999/xhtml">By Sheila F. Buckmaster<div>
,即在xmlns
属性上不加:xhtml
部分吗?否则,xmlns:xhtml
属性就没有效果——它只是声明在节点的范围内,以xhtml:
为前缀的名称属于XHTML命名空间。但是,在其中没有元素或属性节点,只有一个文本节点(“By Sheila F. Buckmaster”)。因此,如果您的意图是使div
元素属于XHTML命名空间,则应省略xmlns:xhtml
属性末尾的:xhtml
。我说的对吗? - Armen Michaeli