通过XSLT和空元素删除XML中的空标记
问题描述:
我遇到以下问题。 我有这样通过XSLT和空元素删除XML中的空标记
<p>
<span class="dateline">City</span><p>
<p>
<em>City.</em>some text
</p>
</p><p>
<p/>
</p>
[... unknown number of other nested paragraphs with text ...]
</p>
一个XML文件,我希望它看起来像:
<p>
<span class="dateline">City</span>
<em>City.</em>some text
</p>
所以我必须去到每片叶子对标签,并采取一切并且只要有父p标签,就将其移动到父p标签。 然后我会删除所有空的p标签。
这怎么能用xslt 1.0来完成?
答
我会写一个身份转换(如果你不知道那是什么,看看它,因为它是值得学习),然后添加两个模板的段落:一个match="p"
匹配未嵌套p
元素其他p
元素,以及match="p[ancestor::p]"
与其他人匹配。第一个模板只是对标识模板的明确重述(也就是说,模板可以在不改变功能的情况下被省略;我只会将其包括在内以便明确处理所有段落)。第二个省略了xsl:copy
指令,只是将模板应用于所有的孩子。
+0
教学完善。 – kjhughes
答
<!-- This template preserve all elements without template -->
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<!-- This template remove all elements without childs (you can replace * by p)-->
<xsl:template match="*[not(node())]"/>
<!-- This template remove p inside other p but preserve all childs -->
<xsl:template match="p[parent::p]">
<xsl:apply-templates />
</xsl:template>
除了手动编辑,你有什么尝试?请发布代码。 – lit
欢迎使用堆栈溢出。如果你展示了你所尝试过的东西,那么你很可能会对这些问题做出很好的回答,并以允许其他人重现问题的形式出现(如果你不知道从哪里开始,这当然很难)。不显示你的工作会给人留下你没有做过的印象,只希望别人为你做你的工作。在[SO帮助文件](http://stackoverflow.com/help/how-to-ask)以及Eric Raymond和Rick Moen的文章[如何以智能的方式提问]中提供有效问题的建议很好( http://catb.org/~esr/faqs/smart-questions.html)。 –