如何使用xslt使用for-each方法解析同一级别的两个xml标记?

时间:2010-03-03 10:55:55

标签: xslt

我正在使用xslt转换xml。

原始XML

<Content>
  <book>
     <customData>
          <CustomDataElement>
             <title>book-name</title>
             <value>Java</value>
          </CustomDataElement>
          <CustomDataElement>
             <title>genre</title>
             <value>Programming</value>
          </CustomDataElement>
     </customData>
  </book>
  <authors>
    <author>
       <name>authorOne</name>
       <country>US</country>
    </author>
  </authors>
  <book>
     <customData>
          <CustomDataElement>
             <title>book-name</title>
             <value>Stranger</value>
          </CustomDataElement>
          <CustomDataElement>
             <title>genre</title>
             <value>Fiction</value>
          </CustomDataElement>
     </customData>
  </book>
  <authors>
    <author>
       <name>authorthree</name>
       <country>UK</country>
    </author>
  </authors>
</Content>

和我的xslt如下

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="/">
<xsl:for-each select="Content/book">
<media>
    <book>
<xsl:apply-templates select="customData/CustomDataElement[title = 'book-name']" />
    </book>

    <genre>
<xsl:apply-templates select="customData/CustomDataElement[title = 'genre']" />
    </genre>
    <author>
    <xsl:value-of select="../authors/author/name" />
    </author>
</media>
</xsl:for-each>
</xsl:template>

<xsl:template match="CustomDataElement">
<xsl:value-of select="value" />
</xsl:template>
</xsl:stylesheet>

这使我的输出为

<?xml version="1.0"?>
<media>
   <book>Java</book>
   <genre>Programming</genre>
   <author>authorOne</author>
</media>
<media>
   <book>Stranger</book>
   <genre>Fiction</genre>
   <author>authorOne</author>
</media>

我希望作者的姓名来自“authors \ author”标签,该标签位于book标签之后。

我在这里缺少什么?请帮忙

1 个答案:

答案 0 :(得分:2)

而不是

<xsl:value-of select="../authors/author/name" />

<xsl:value-of select="following-sibling::authors[1]/author/name" />

由于您位于book节点的上下文中,因此此xpath表示要查找第一个([1])后续兄弟authors节点,并选择{{1}从那起。