xml - 如何使用 xslt 1.0 逐行输出文本节点值?

标签 xml xpath xslt-1.0

我有一个类似这样的 xml 文件:

<Messages>
   error message 1

   error message 2 
</Messages>

我希望输出为:

Error 1: 
error message 1

Error 2:
error message 2

我使用的是 xslt 1.0,我尝试过:

<?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="html" omit-xml-declaration="yes"/>

<xsl:template match="Messages">
    <h3>Error 1:</h3>
    <xsl:value-of select="substring-before(./text(), '&#10;')"/>
    <h3>Error 2:</h3>
    <xsl:value-of select="substring-after(./text(), '&#10;')"/>
</xsl:template>
</xsl:stylesheet>

但是它什么也没给我返回...有人可以帮我解决这个问题吗?谢谢!

最佳答案

您可以使用这个递归模板来实现:

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

  <xsl:output method="html" omit-xml-declaration="yes"/>

  <xsl:template match="Messages" name="outputError">
    <xsl:param name="index" select="1"/>
    <xsl:param name="source" select="text()"/>
    <xsl:variable name="thisLine" select="normalize-space(substring-before($source, '&#10;'))"/>
    <xsl:variable name="theRest" select="substring-after($source, '&#10;')"/>
    <xsl:choose>
      <xsl:when test="$thisLine">
        <h3>Error <xsl:value-of select="$index"/>:</h3>
        <span><xsl:value-of select="$thisLine"/></span>
        <xsl:call-template name="outputError">
          <xsl:with-param name="index" select="$index + 1"/>
          <xsl:with-param name="source" select="$theRest"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:when test="$theRest">
        <xsl:call-template name="outputError">
          <xsl:with-param name="index" select="$index"/>
          <xsl:with-param name="source" select="$theRest"/>
        </xsl:call-template>
      </xsl:when>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

我将实际错误包装在 <span> 中元素只是为了清楚地将它们与空格分开,你当然可以使用 <p> , <div>如果您愿意,也可以根本没有任何元素。

关于xml - 如何使用 xslt 1.0 逐行输出文本节点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071392/

相关文章:

xml - 使用翻译功能删除 XSLT 中的单词 'and'

java - Android应用程序甚至无法运行。Logcat显示 "android.widget.text view cannot be cast to android.widget.Button."

c# - 如何强制浏览器下载 xml 文件?

ruby - 如何将 Nokogiri 与 Ruby 结合使用来替换现有 xml 中的值?

xml - 引用节点集而不复制它

java - 将 xml 从第 n 个元素拆分为第 x 个元素

xml - 有没有更好的方法获取 XPath 查询结果的父节点?

android - 添加到 RelativeLayout 时更改 GridView

python - 如何找到Selenium WebDriver的XPath?

xml - XPath 选择仅包含特定类型子项的父项?