使用 XSLT 检查空的 XML 元素 [英] Check for empty XML element using XSLT

查看:18
本文介绍了使用 XSLT 检查空的 XML 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 XML

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema">
<Number1>
</Number1>
<Number2>11</Number2>
<Number3>12</Number3>
</ns0:Root>

在这种情况下,我为 Number1 获取 ENTER\r\n.我想编写一些 XSLT 来检查节点是否包含 ENTER\r\n,然后替换它 .

In this case I am getting ENTER or \r\n for Number1. I want to write some XSLT to check if a node contains ENTER or \r\n and then replace it <Number1 />.

谁能帮我为此编写 XSLT?

Can anyone help me to write the XSLT for this?

推荐答案

空元素"的含义有多种可能的定义.

让我们定义一个空元素,它没有任何元素节点子节点,并且其字符串值为空字符串,或者仅由空格字符(' '、CR、NL)组成.

Let's define an empty element as one that doesn't have any element nodes children and whose string value is the empty string, or consists only of white space characters (' ', CR, NL).

然后检查给定元素是否为空,使用:

not(*) and not(normalize-space())

这假定元素是计算 XPath 表达式时的上下文节点.

This assumes that the element is the context node when the XPath expression is evaluated.

在这种情况下,我收到 Number1 的ENTER"或\r\n".我想要编写 XSLT 以检查节点是否包含ENTER"或\r\n"然后替换它.

In this case I am getting "ENTER" or "\r\n" for Number1. I want to write XSLT to check if node contain "ENTER" or "\r\n" then replace it .

您尚未指定应替换此文本节点的内容,因此在此解决方案中,我假设应将文本节点替换为空字符串(已删除):

You haven't specified with what this text node should be replaced, so in this solution I am assuming the text node should be replaced with the empty string (deleted):

<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(normalize-space())]">
  <xsl:element name="{name()}" namespace="{namespace-uri()}"/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema">
    <Number1>
    </Number1>
    <Number2>11</Number2>
    <Number3>12</Number3>
</ns0:Root>

产生想要的结果:

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema">
   <Number1/>
   <Number2>11</Number2>
   <Number3>12</Number3>
</ns0:Root>

这篇关于使用 XSLT 检查空的 XML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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