使用XSLT检查节点是否存在

Kev*_*vin 6 xml xslt

首先,我想问一下,XML节点的以下两个语句之间是否存在差异:

  1. 检查节点是否为空节点;
  2. 检查节点是否存在;

假设我有一个像这样的XML文件:

<claim_export_xml>
<claim_export_xml_row>
    <claim_number>37423</claim_number>
    <total_submitted_charges>0</total_submitted_charges>
    <patient_control_no/>

    <current_onset_date>2009-06-07 00:00:00</current_onset_date>
Run Code Online (Sandbox Code Playgroud)

我想检查"current_onset_date"节点是否存在,我使用了以下XSLT:

<xsl:for-each select="claim_export_xml_row ">
       <xsl:if test="claim_number =$mother_claim_no and /current_onset_date "> 
Run Code Online (Sandbox Code Playgroud)

for-each循环是我必须承受的一些逻辑,以便循环工作.但是在运行这个XSLT之后,我确实得到了错误的结果,上面的xml数据不会被我的XSLT抓取.但我不认为使用"current_onset_date =''"也是正确的,因为它正在测试"current_onset_date是否包含任何内容".

谁能告诉我我的错误在哪里,也帮助我在开始时列出我的问题,谢谢!

Dim*_*hev 17

我想问一下,XML节点的以下两个语句之间是否有区别:

1.检查节点是否为空节点;

2.检查节点是否存在;

这些需要不同的表达式来测试:不存在的节点不是空节点:

current_onset_date 
Run Code Online (Sandbox Code Playgroud)

这将选择current_onset_date当前节点的所有子节点.它的布尔值是true()if和仅当至少有一个这样的子元素存在时,false()否则.

current_onset_date/text()
Run Code Online (Sandbox Code Playgroud)

这将选择current_onset_date当前节点的任何子节点的任何文本节点子节点.如果没有,则其布尔值为false(),否则为 - true(),

即使元素没有文本节点作为子元素,它仍然可能具有非空字符串值,因为它可能具有元素作为后代,并且这些元素后代中的一些可能具有文本节点子元素.

current_onset_date[not(string(.))]
Run Code Online (Sandbox Code Playgroud)

这将选择current_onset_date当前节点的任何子节点,其中包含空字符串('')作为其字符串值.这可能适合"空元素".

如果为空,则表示其字符串值为空或仅为空格的元素,则此表达式为:

current_onset_date[not(normalize-space())]
Run Code Online (Sandbox Code Playgroud)

这将选择current_onset_date当前节点的任何子节点,它们具有空字符串('')或仅包含空格的字符串作为其字符串值.

谁能告诉我我的错误在哪里

在你的代码中:

<xsl:for-each select="claim_export_xml_row ">                            
   <xsl:if test="claim_number =$mother_claim_no 
                              and /current_onset_date ">      
Run Code Online (Sandbox Code Playgroud)

test属性中的表达式总是false()因为/current_onset_date意味着:名为"current_onset_date"的top元素(文档),但是你的case中的top元素被命名 claim_export_xml

你可能想要:

claim_number =$mother_claim_no and current_onset_date 
Run Code Online (Sandbox Code Playgroud)

如果你想让元素"非空",那么:

    claim_number =$mother_claim_no 
   and 
    current_onset_date[normalize-space()]  
Run Code Online (Sandbox Code Playgroud)

  • +1更正确的答案.我已经停止写我的了. (2认同)

biz*_*lop 4

它应该可以工作,只是你有两个“和”,并且在 current_onset_date 之前不需要前导 / 。

如果您还想检查是否为空,可以使用:

<xsl:for-each select="claim_export_xml_row ">
   <xsl:if test="claim_number =$mother_claim_no and current_onset_date != ''">
Run Code Online (Sandbox Code Playgroud)

其工作原理是元素的字符串值是其内部所有文本的串联,因此该表达式将仅选择current_onset_date存在且包含非空字符串的行。如果你想排除只包含空格的元素,你可以这样写:

<xsl:for-each select="claim_export_xml_row ">
   <xsl:if test="claim_number =$mother_claim_no and normalize-space( current_onset_date ) != ''">
Run Code Online (Sandbox Code Playgroud)