XPath / XSLT删除空标签 [英] XPath/XSLT Remove Empty Tags

查看:214
本文介绍了XPath / XSLT删除空标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

 < p>< p> < / p为H. 

如何使用xpath函数和xslt模板执行此操作?

解决方案

此转换(覆盖身份规则):

 < xsl:stylesheet version =1.0
xmlns: XSL = http://www.w3.org/1999/XSL/Transform >
< xsl:output omit-xml-declaration =yesindent =yes/>

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

< xsl:template match =* [not(*)and not(text()[normalize-space()])]/>
< / xsl:stylesheet>

应用于以下XML文档

 < t> 
< a>
< b>
< c />
< / b>
< / a>
< p>< / p>
< p> < / p为H.
< p>文字< / p>
< / t>

正确地产生想要的结果

 < t> 
< a>
< b />
< / a>
< p>文字< / p>
< / t>

记住:使用和覆盖身份规则/模板是最基本的和强大的XSLT设计模式。对于大多数节点将被不变地复制并且只有一些特定节点需要被改变,删除,重命名等等的各种问题,这是正确的选择。

注意:@Abel在他的评论中建议,这个解决方案的一些部分需要进一步解释:


对于不熟悉或好奇的人: not(*)表示:没有孩子
元素; not(text()[normalize-space()])表示:没有文本节点
和非空白文本。 p>


I would like to remove tags which contain only whitespace/newline/tab chars, as below:

<p>    </p>

How would you do this using xpath functions and xslt templates?

解决方案

This transformation (overriding the identity rule):

<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="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="*[not(*) and not(text()[normalize-space()])]"/>
</xsl:stylesheet>

when applied to the following XML document:

<t>
 <a>
  <b>
    <c/>
  </b>
 </a>
 <p></p>
 <p>  </p>
 <p>Text</p>
</t>

correctly produces the wanted result:

<t>
   <a>
      <b/>
   </a>
   <p>Text</p>
</t>

Remember: Using and overriding the identity rule/template is the most fundamental and powerful XSLT design pattern. It is the right choice for a variety of problems where most of the nodes are to be copied unchanged and only some specific nodes need be altered, deleted, renamed, ..., etc.

Note: @Abel in his comment recommends that some bits of this solution need to be further explained:

For the uninitiated or curious: not(*) means: not having an child element; not(text()[normalize-space()]) means: not having a text-node with non - white-space-only text.

这篇关于XPath / XSLT删除空标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆