xml - XSL 到 XML 循环问题

标签 xml xslt

我需要循环一个 XML 文档。没问题。
当我需要刚刚跳过的上一行文本时,问题就出现了。

XML 看起来像这样

<lines>
  <line>
    <id>1</id>
    <text>Some fancy text here 1</text>
  </line>
  <line>
    <id></id>
    <text>This I need in the next line with a ID</text>
  </line>
  <line>
    <id></id>
    <text>Also need this.</text>
  </line>
  <line>
    <id>4</id>
    <text>Here we go</text>
  </line>
</lines>

输出 XML 文件需要如下所示

<output>
  <line>
    <id>1</id>
    <note>Some fancy text here 1</note>
  </line>
  <line>
    <id>4</id>
    <note>Here we go</note>
    <extra>
      <note>This I need in the next line with a ID</note>
      <note>Also need this.</note>
    </extra>
  </line>
</output>

我目前拥有的 XSL 很容易整理出没有设置 ID 的行。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <output>
    <xsl:for-each select="lines/line">
      <xsl:if test="id/text() &gt; 0">
        <line>
          <id>
            <xsl:value-of select="id" />
          </id>
          <note>
            <xsl:value-of select="text" />
          </note>
        </line>
      </xsl:if>
    </xsl:for-each>
    </output>
  </xsl:template>
</xsl:stylesheet>

最佳答案

您需要选择前一个兄弟;有一个example here .

基本上,您的 xpath 语法类似于(未测试):

preceding-sibling::NodeName[1]

关于xml - XSL 到 XML 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290229/

相关文章:

android - 颜色 xml : "Attribute is missing the Android namespace prefix"

php - CakePHP 中的自动站点地图

javascript - XSLT:在元素标签中输出Javascript

xml - XSL : why doesn't output indent work?

python - soap 1.2 消息的 http header 中应该包含什么内容类型?

python - 未使用 scrapy 以 XML 或 JSON 形式抓取数据

algorithm - xsl 中的自定义分组

xml - XSL 转换后 LaTeX 表不适合线宽

java - 从 Hibernate Annotations 切换到 hbm.xml 文件时出错

java - 使用 xpath 根据另一个属性的值检索属性值