1

所以这就是我的 XML 的样子。这非常简单,当然只是想为每个链接布置一堆指向其他 XML 文件的链接,每个链接具有不同的名称/标题:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="index.xsl"?>
<playToc>
    <play>a_and_c.xml</play>
    <play>all_well.xml</play>
    <play>as_you.xml</play>
    <play>com_err.xml</play>
    <play>coriolan.xml</play>
    <play>cymbelin.xml</play>
    <name>Title 1</name>
    <name>Title 2</name>
    <name>Title 3</name>
    <name>Title 4</name>
    <name>Title 5</name>
    <name>Title 6</name>
</playToc>

很简单,对吧?这是我的 XSL:

<?xml version="1.0" encoding="ISO-8859-1"?>

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

<xsl:template match="playToc">
<html>
<body style="text-align:center;">

<xsl:apply-templates select="play"></xsl:apply-templates>

</body>
</html>
</xsl:template>

<xsl:template match="play">

<xsl:variable name="URL">
    <xsl:value-of select="."/> 
</xsl:variable>

<xsl:variable name="TITLE">
    <xsl:value-of select="../name"/> 
</xsl:variable>

<a href="{$URL}"><xsl:value-of select="$TITLE"/></a>
<br />
</xsl:template>

</xsl:stylesheet>

这是输出:

Title 1
Title 1
Title 1
Title 1
Title 1
Title 1

当我希望这是输出时,当然:

Title 1
Title 2
Title 3
Title 4
Title 5
Title 6

任何帮助都会很棒!非常感谢!

4

2 回答 2

2

好吧,XML输入的结构很差,但是您可以通过这样做来解决这个问题

<xsl:template match="play">
  <xsl:variable name="pos" select="position()"/>
  <a href="{.}">
    <xsl:value-of select="../name[position() = $pos]"/>
  </a>
  <br/>
</xsl:template>

确保将其保留<xsl:apply-templates select="play"/>在另一个模板中,否则该方法position()将不起作用。

于 2012-10-21T09:49:10.450 回答
1
<xsl:variable name="TITLE">      
 <xsl:value-of select="../name"/>   
</xsl:variable>

你的问题就在这里。

的字符串值../name是初始上下文(当前)节点的父节点的第一个子节点的字符串值。 name

您真正想要的是获取与当前 ( ) 节点name位置相同的子节点的值。play

这个完整而短暂的转变

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="play">
   <xsl:variable name="vPos" select="position()"/>
     <a href="{.}">
      <xsl:value-of select="../name[$vPos]"/>
     </a><br />
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

当应用于提供的源 XML 文档时

<playToc>
    <play>a_and_c.xml</play>
    <play>all_well.xml</play>
    <play>as_you.xml</play>
    <play>com_err.xml</play>
    <play>coriolan.xml</play>
    <play>cymbelin.xml</play>
    <name>Title 1</name>
    <name>Title 2</name>
    <name>Title 3</name>
    <name>Title 4</name>
    <name>Title 5</name>
    <name>Title 6</name>
</playToc>

产生想要的正确结果

<a href="a_and_c.xml">Title 1</a>
<br/>
<a href="all_well.xml">Title 2</a>
<br/>
<a href="as_you.xml">Title 3</a>
<br/>
<a href="com_err.xml">Title 4</a>
<br/>
<a href="coriolan.xml">Title 5</a>
<br/>
<a href="cymbelin.xml">Title 6</a>
<br/>

请注意

  1. 完全没有必要使用xsl:apply-templates

  2. 只有一个模板。

于 2012-10-21T13:56:22.687 回答