当前位置: 动力学知识库 > 问答 > 编程问答 >

xml - XSLT: Matching elements with namespaces not working

问题描述:

I'm trying to convert a database of XML song lyrics into HTML with XSLT. My XML begins like this:

<?xml version='1.0' encoding='utf-8'?>

<song xmlns="http://openlyrics.info/namespace/2009/song" version="0.8" createdIn="OpenLP 2.0.1" modifiedIn="OpenLP 2.0.1" modifiedDate="2012-03-14T02:21:52">

<properties>

<titles>

<title>Amazing Grace</title>

</titles>

<authors>

<author>John Newton</author>

</authors>

</properties>

<lyrics>

<verse name="v1">

<lines>Amazing grace, how sweet the sound<br/>That saved a wretch like me<br/>I once was lost, but now am found<br/>Was blind but now I see</lines>

I know from other posts that I need to add the above namespace into my XSLT. I tried, and my XSLT looks like this:

<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

xmlns:lyrics="http://openlyrics.info/namespace/2009/song">

<xsl:template match="lyrics:song">

<h3><xsl:value-of select="properties/titles/title"/></h3>

<h4><xsl:value-of select="properties/authors/author"/></h4>

<xsl:for-each select="lyrics/verse">

<xsl:copy-of select="lines" /><br /><br />

</xsl:for-each>

</xsl:template>

</xsl:stylesheet>

Unfortunately, this code still isn't working. My XSLT only works when I eliminate the xmlns entry in my XML and match "song" directly. Can anyone point out what I'm doing wrong in regards to the xmlns namespace that I titled "lyrics?" I'm very new at XML/XSLT. Thanks in advance!

网友答案:

You need to use the namespace prefix "lyrics" at any element name which belong to the namespaces "http://openlyrics.info/namespace/2009/song". And this are all element names because it is the default namespace. Try somenthing like this (not tested):

<xsl:template match="lyrics:song">
  <h3><xsl:value-of select="lyrics:properties/lyrics:titles/lyrics:title"/></h3>
  <h4><xsl:value-of select="lyrics:properties/lyrics:authors/lyrics:author"/></h4>
  <xsl:for-each select="lyrics:lyrics/lyrics:verse">
  <xsl:copy-of select="lyrics:lines" /><br /><br />
  </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
分享给朋友:
您可能感兴趣的文章:
随机阅读: