Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

xslt - How do i remove all linebreaks?

I have something like this:

<node TEXT="   txt A   "/>
<node TEXT="

       txt X

"/>
<node>
   <html>
      <p>
        txt Y
      </p>
   </html>
</node>
<node TEXT="txt B"/>

and i want to use XSLT to get this:

txt A
txt X
txt Y
txt B

I want to strip all useless whitespaces and linebreaks of @TEXT's and CDATA's. The only XML-input that is giving structure to the output are the <node>-tags.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following transformation:

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

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

<xsl:template match="node/@TEXT | text()">
  <xsl:if test="normalize-space(.)">
    <xsl:value-of select=
     "concat(normalize-space(.), '&#xA;')"/>
  </xsl:if>

  <xsl:apply-templates />
</xsl:template>

</xsl:stylesheet>

when applied against this XML document

<t>
<node TEXT="   txt A   "/>
<node TEXT="       txt X"/>
<node>
    <html>
        <p>        txt Y      </p>
    </html>
</node>
<node TEXT="txt B"/>
</t>

produces the wanted result:

txt A
txt X
txt Y
txt B

Do note the use of the standard XPath function normalize-space(), which strips off all leading and trailing spaces and replaces every sequence of other spaces with just one space.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...