使用 XSLT 删除节点后删除空行 [英] Getting rid of empty lines after deleting nodes using XSLT
问题描述
我正在使用 XSLT 在 XML 文档中进行非常简单的转换.我只想删除具有特定名称的所有元素节点.碰巧在我的源文档中,所有这些节点都位于文档的末尾,但是转换后,虽然节点按照我的意图消失了,但它们的位置却有很多空行.
I am using XSLT to make a very simple transformation in a XML document. I just want to delete all the element nodes with a particular name. It happens that in my source document all these nodes are located at the end of the document, but after the transformation, although the nodes have disappeared as I intended, there are lots of empty lines in their place.
这完全是一个表面问题,因为我通过转换完成了我想要的,但出于好奇:我怎样才能摆脱这些空行?这是我用于转换的 XSL 文件(我要删除的元素名为关系"):
This is strictly a cosmetic issue since I accomplished what I wanted with the transformation, but out of curiosity: how can I get rid of these empty lines ? This is the XSL file I used for the transformation (the element I wanted to remove is named "relations"):
<?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="xml" />
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="relation"/>
</xsl:stylesheet>
推荐答案
原因在于与已删除元素直接同级的纯空白文本节点.
解决方案:只需添加此 XSLT 指令即可删除任何纯空白文本节点——甚至在转换开始之前:
Solution: Simply add this XSLT instruction to remove any white-space-only text nodes -- even before the transformation is started:
<xsl:strip-space elements="*"/>
结果可能会丢失缩进——如果是这样,请添加:
The result may lose indentation -- if so, add this:
<xsl:output omit-xml-declaration="yes" indent="yes"/>
完整的转化变成:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="relation"/>
</xsl:stylesheet>
应用于此 XML 文档时(未提供!):
<nums>
<num>01</num>
<num>02</num>
<num>03</num>
<num>04</num>
<num>05</num>
<num>06</num>
<num>07</num>
<num>08</num>
<num>09</num>
<num>10</num>
<relation/>
<relation/>
<relation/>
<relation/>
<relation/>
<relation/>
<relation/>
<relation/>
</nums>
产生想要的、正确的结果(没有尾随空格):
<nums>
<num>01</num>
<num>02</num>
<num>03</num>
<num>04</num>
<num>05</num>
<num>06</num>
<num>07</num>
<num>08</num>
<num>09</num>
<num>10</num>
</nums>
这篇关于使用 XSLT 删除节点后删除空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!