简体   繁体   English

如何检查XML标记中的属性是否为未定义的JavaScript(Mirth Connect)

[英]how do i check if attribute from XML tag is undefined JavaScript (Mirth Connect)

I want to check if attribute in XML tag is present or not. 我想检查XML标签中的属性是否存在。

here is the sample xml tag: <value @code=""> 这是示例xml标记: <value @code="">

i Want to check following conditions.. 我想检查以下条件。

  1. if tag is present. 如果存在标签。
  2. if @code is present. 如果存在@code。
  3. if @code is null. 如果@code为null。

currently I am checking condition as below: 目前,我正在检查情况,如下所示:

 if(msg['value']) { hasValue='true'; if(msg['value']['@code']) { hasCode='true'; }else { hasCode='false'; } } 

but this condition returns hasValue flag always true. 但是此条件返回的hasValue标志始终为true。 Even if @code is missing/undefined. 即使@code丢失/未定义。

Is there a way to check if @code is undefined/missing? 有没有办法检查@code是否未定义/缺失?

You can use hasOwnProperty() to check for the existence of an element or attribute, and you can use .toString() to check whether the attribute value is empty or not. 您可以使用hasOwnProperty()检查元素或属性是否存在,还可以使用.toString()检查属性值是否为空。

if(msg.hasOwnProperty('value')) {
  hasValue='true';

  if(msg.value.hasOwnProperty('@code') && msg.value['@code'].toString()) {
    hasCode='true';
  } else {
    hasCode='false';
  }
}

hasOwnProperty is typically not used for xml (for people following the javascript tag, mirth embeds the Mozilla Rhino javascript engine, which uses the deprecated e4x standard for handling xml.) hasOwnProperty does not behave as expected when there are multiple child elements named value . hasOwnProperty通常不用于xml(对于使用javascript标签的用户,mirth嵌入了Mozilla Rhino javascript引擎,该引擎使用不推荐使用的e4x标准来处理xml。)当存在多个名为value子元素时,hasOwnProperty的行为不符合预期。 From the naming convention, I'm assuming it is possible to have multiple values with different codes. 根据命名约定,我假设可以使用不同的代码来包含多个值。

This will create an array for hasCode that holds a boolean for each occurrence of a child element named value. 这将为hasCode创建一个数组,该数组为每次出现的名为value的子元素保留一个布尔值。

var hasCode = [];
var hasValue = msg.value.length() > 0;
for each (var value in msg.value) {
    // Use this to make sure the attribute named code exists
    // hasCode.push(value['@code'].length() > 0);

    // Use this to make sure the attribute named code exists and does not contain an empty string
    // The toString will return an empty string even if the attribute does not exist
    hasCode.push(value['@code'].toString().length > 0);
}

(while length is a property on strings, it is a method on xml objects, so the parentheses are correct.) (虽然length是字符串的属性,但是它是xml对象的方法,所以括号是正确的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM