我尝试使用XSLT将XML转换为明文文件以加载到数据库中。但是,我需要的其中一个元素可能包含我需要保留的HTML格式文本,以及我不知道的换行符和空格。我也不想要XML命名空间。
文件很大且更复杂,但下面的例子应该包含这个问题。
XML:
<outer xmlns="urn:site-org:v3/m2" >
<inner>
<text>
<p>This is text with markup</p>
<p>This is text with <i>more</i> markup</p>
</text>
</inner>
<inner>
<text>
Need text with no markup also
</text>
</inner>
</outer>
期望的输出:
<p>This is text with markup</p><p>This is text with <i>more</i> markup</p>
Need text with no markup also
使用text的输出格式,normalize-space()会清除所有换行符和空格,但也会删除标记。
我尝试过使用xml输出和xsl:copy-of,但这会留下换行符,命名空间和字符会对我的其他一些输出进行编码(&
- &gt; {{1这是不受欢迎的。
提前感谢任何想法!
答案 0 :(得分:3)
删除空格而不删除元素的关键是正确使用模板,只删除文本节点中的空格,而不是整个元素。
我并非100%明确您的要求,但这至少应该非常接近:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:m2="urn:site-org:v3/m2">
<xsl:output method="xml" indent="no" omit-xml-declaration="yes" />
<!-- Remove any whitespace between elements -->
<xsl:strip-space elements="*" />
<xsl:template match="m2:text">
<xsl:apply-templates />
<!-- Newline -->
<xsl:text>
</xsl:text>
</xsl:template>
<!-- Copy elements beneath text elements, without their namespace-->
<xsl:template match="m2:text//*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@* | node()" />
</xsl:element>
</xsl:template>
<!-- Copy attributes beneath text elements-->
<xsl:template match="m2:text//@*">
<xsl:copy />
</xsl:template>
<!-- Text nodes in HTML content - normalize space but escape entities -->
<xsl:template match="m2:text[.//*]//text()" priority="5">
<xsl:value-of select="normalize-space()"/>
</xsl:template>
<!-- Text nodes in HTML content - normalize space and don't escape entities -->
<xsl:template match="m2:text//text()">
<xsl:value-of select="normalize-space()" disable-output-escaping="yes"/>
</xsl:template>
</xsl:stylesheet>
在以下输入上运行时:
<outer xmlns="urn:site-org:v3/m2" >
<inner>
<text>
<p class="snazzy">This is text with markup and &&& ampersands</p>
<p>This is text with <i>more</i> markup</p>
</text>
</inner>
<inner>
<text>
Need text with no markup also and some &&& ampersands
</text>
</inner>
</outer>
结果是:
<p class="snazzy">This is text with markup and &&& ampersands</p><p>This is text with<i>more</i>markup</p>
Need text with no markup also and some &&& ampersands