xslt - 如何使用 XSL 获取纯文本和换行符

标签 xslt

有了这个输入

<?xml version="1.0" encoding="UTF-8"?> <data> 
This is a senstence   
this is another sentence

<section>
        <!--comment --><h2>my H2</h2>     <p>some paragraph</p>             <p>another paragraph</p>                 
    </section> </data>

我需要应用 XSL 样式表来获取纯文本,尊重换行符,并删除前面的空格。所以,在网上搜索了几个样本后,我尝试了这个,但它对我不起作用。对不起,我不熟悉 XSL,我想我会问。

尝试过 XSL,但它不起作用。有任何想法吗?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="UTF-8"/>
    <xsl:strip-space elements="*" />

        <xsl:template match ="@* | node()">
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>    
        </xsl:template>

        <xsl:template match="h1|h2">
            <xsl:text>
            </xsl:text>
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>  
        </xsl:template>
</xsl:stylesheet>

这是应用 XSL 后的输出。
如您所见,全部为一行,而不是回车。
This is a sentence this is another sentence m H2some paragraphTanother paragraph

这是我想要的输出。 H1|H2|H3 中的文本前后应有换行符。
This is a sentence 
this is another sentence 

my H2

some paragraph
another paragraph

最佳答案

您需要一个 xml:space="preserve"保持回车的属性xml:text ,并且在h1的内容前后需要回车和 h2标签:

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

  <xsl:template match ="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="h1|h2">
    <xsl:text xml:space="preserve">
</xsl:text>
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
    <xsl:text xml:space="preserve">
</xsl:text>
  </xsl:template>
</xsl:stylesheet>

在我的情况下,初始文本( This is a senstencethis is another sentence )在单独的行上正确输出(使用 Visual Studio 2012 执行 XSLT)。

你只写了 h标签应该添加回车符 - 在您的示例中 some paragraphanother paragraphp标签,所以没有添加回车,它们在同一行输出。

关于xslt - 如何使用 XSL 获取纯文本和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125287/

相关文章:

基于条件逻辑的 XSLT 过滤节点

java - 无法使用xslt从xml获取所需数据到csv

xml - xpath选择所有 parent 和所有 child

xslt - 在 xslt 2.0 中使用时区将纪元转换为日期和时间

java - 通过 xslt 的文本文件的 mime 类型

xml - 如何正确指定表的 colname?

javascript - 如何使用 JQuery 按属性删除元素

xml - 如何将本地文件路径放入 XSL 属性中

regex - 为什么我需要在正则表达式中使用双花括号?

xslt - 使用 XSLT 删除不需要的空格并返回