0

我一直在尝试使用 XSLT 实现以下输出,但一直在苦苦挣扎。提前感谢您的任何帮助。

<par>
   <run>Line one<break/>
        Line two<break/>
   </run>

   <run>Another para of text<break/>
   </run>

   <run>3rd para but no break</run>    
</par>

 <document>
   <para>Line one</para>
   <para>Line two</para>
   <para>Another para of text</para>
   <para>3rd para but no break</para>
 </document>

谢谢,

多诺

4

2 回答 2

2

这是一个简单的解决方案,它是面向推送的,不需要<xsl:for-each><xsl:if>self::轴。

当这个 XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output omit-xml-declaration="yes" indent="yes" />
  <xsl:strip-space elements="*" />

  <xsl:template match="/*">
     <document>
       <xsl:apply-templates />  
     </document>
  </xsl:template>

  <xsl:template match="run/text()">
     <para>
       <xsl:value-of select="normalize-space()" />
     </para>
  </xsl:template>

</xsl:stylesheet>

...应用于提供的 XML:

<par>
   <run>Line one<break/>
        Line two<break/>
   </run>

   <run>Another para of text<break/>
   </run>

   <run>3rd para but no break</run>    
</par>

...产生了想要的结果:

<document>
  <para>Line one</para>
  <para>Line two</para>
  <para>Another para of text</para>
  <para>3rd para but no break</para>
</document>
于 2012-12-06T01:27:12.633 回答
0

假设您的<run>元素只会包含文本和<break/>元素,并且您想要规范化空格并排除<para>仅包含空格的元素(由您所需的输出建议),以下应该有效:

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

    <xsl:output indent="yes"/>

    <xsl:template match="par">
        <document>
            <xsl:apply-templates select="*"/>
        </document>
    </xsl:template>

    <xsl:template match="run">
        <xsl:for-each select="text()">
            <xsl:if test="normalize-space(self::text()) != ''">
                <para>
                    <xsl:value-of select="normalize-space(self::text())"/>
                 </para>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>
于 2012-12-06T00:56:59.683 回答