【问题标题】:Use XSLT to display multiple attributes with same name使用 XSLT 显示多个同名属性
【发布时间】:2014-07-14 13:48:31
【问题描述】:

我对 xml 和 xslt 的世界还很陌生。我想要做的是使用 xslt 返回在 xml 文件中生成的所有错误消息,每个父级下都有很多错误消息。

以下是 XML 文件的示例:

   <progress_file>
        <read_leg>
            <info>Successfully read face ID 225</info>
            <info>successfully read face ID 226</info>
            <error>unable to read face ID 227</error>
            <error>unable to read face ID 228</error>
        </read_leg>
        <write_leg>
            <info>Successfully created face ID 225</info>
            <info>successfully created face ID 226</info>
            <error>unable to write face ID 227</error>
            <error>unable to write face ID 228</error>
        </write_leg>
    </progress_file>

使用的 XSLT 是:

<?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="/">
      <xsl:for-each select="progress_file/read_leg">
        <xsl:value-of select="error"/>
      </xsl:for-each>
      <xsl:for-each select="progress_file/write_leg">
        <xsl:value-of select="error"/>
      </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

输出只返回每个区域的第一个值。我认为这就是逻辑所暗示的,即“对于每个写入腿,返回错误消息”,这并不意味着它会检查是否存在多种情况。

我还没有看到任何具有多个同名属性的地方,我还没有遇到可以使用它的 XSL 元素,所以我有点卡住了。有什么建议吗?

还有一个问题,是否可以在输出行之间换行?

谢谢。

【问题讨论】:

  • @EeroHelenius 请不要编辑OP的代码;你不知道原件是否正确。
  • @michael.hor257k:我很抱歉,感谢您指出这一点。我只是假设代码中有错字,因为它与示例输入不对应。但你是对的,做出这样的假设可能并不安全——我以后会知道的。

标签: xml xslt xslt-1.0


【解决方案1】:

这是一种选择:

样式表

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

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" version="1.0" encoding="utf-8"/>

  <!-- The XML entity for a line feed -->
  <xsl:variable name="linefeed" select="'&#10;'"/>

  <!-- Match the root node -->
  <xsl:template match="/">
    <!-- Apply templates for all <error> nodes. -->
    <xsl:apply-templates select="progress_file/read_leg/error | progress_file/write_leg/error"/>
  </xsl:template>

  <xsl:template match="error">
    <!-- Concatenate the value of the current node and a line feed. -->
    <xsl:value-of select="concat(., $linefeed)"/>
  </xsl:template>
</xsl:stylesheet>

输出

unable to read face ID 227
unable to read face ID 228
unable to write face ID 227
unable to write face ID 228

【讨论】:

  • 假设他希望处理progress_file 下的所有潜在错误元素,您可以将匹配缩短为progress_file/*/error
  • "read_leg first and then write_leg" 是一种误解。 select 节点的顺序无关紧要,生成的节点集在 XSLT 中将始终按文档顺序排列。 (顺便说一句,XSLT 2.0 也是如此:单个 XPath 表达式将产生一个按文档顺序排列的序列。但是,您也可以构建自定义排序的序列。)
  • @MatthewGreen 仅仅因为你可以,并不意味着你应该。
  • @Tomalak:您说的完全正确,感谢您指出。我在想, 而不是|
  • 谢谢,这会输出正确的数据。但是换行选项不起作用。我已经在 IE 中打开了 XML,并尝试在 W3 学校网站link 上使用 TryIt 编辑器,所有信息都显示在一行上。知道为什么会这样吗?
猜你喜欢
  • 1970-01-01
  • 2011-07-11
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
相关资源
最近更新 更多