开发者

select a node with an xmlns?

I am trying to select all of the links in a xhtml document in xsl. Some of the anchor tags have the namespace declaration xmlns="http://www.w3.org/1999/xhtml" in them. These are not selected. e.g. with this xml doc:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl.xsl"?>
<root>
<item>
this iz sum text and it haz sum <a xmlns="http://www.w3.org/1999/xhtml" href="http://cheezburger.com/">linx</a> in it.
Teh linx haz piks of <a href="http://ica开发者_Python百科nhascheezburger.com/">kittehs</a> in dem.
</item>
</root>

and this xsl:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<dl>
<xsl:for-each select="//root/item/a">
    <dd><xsl:value-of select="."/></dd>
    <dt><xsl:value-of select="@href"/></dt>
</xsl:for-each>
</dl>
</html>
</xsl:template>
</xsl:stylesheet>

Only the second link is selected. Can someone explain what is going on here and how I might fix it?


If you need both nodes, which are in different namespaces, use:

/root/item/*[local-name() = 'a']

However, this should seldomly happen, normally, you want a node from only one namespace:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:example="http://www.w3.org/1999/xhtml"
  >
....
<xsl:for-each select="/root/item/example:a">


The a elements are in 2 different namespaces, the default namespace and the xhtml namespace. If you move the XPath outside of the xhtml formatting, you can use both namespaces to search:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <xsl:variable name="links" xmlns:xhtml="http://www.w3.org/1999/xhtml"
                  select="//root/item/(a | xhtml:a)"/>

    <html xmlns="http://www.w3.org/1999/xhtml">
      <dl>
        <xsl:for-each select="$links">
          <dd><xsl:value-of select="."/></dd>
          <dt><xsl:value-of select="@href"/></dt>
        </xsl:for-each>
      </dl>
    </html>
  </xsl:template>

</xsl:stylesheet>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜