如何在foreach中处理xml? ->不兼容的类型:预期的“ xml”,找到的“xml | string”

问题描述

有人可以帮助我了解xml元素相对于foreach语句如何工作吗?

下面的示例代码显示了两种不同的方法来访问xml元素“ Child”。首先,直接访问所有“孩子”(第3行),然后仅访问foreach循环内的特定“人”的“孩子”(第5行)。

  1. 为什么会出现编译错误
  2. 在遍历所有“人”时,我需要做什么以访问特定“人”的所有“子”元素?

test.bal:

function foo(xml input) returns boolean{
  xml listofPersons = input/<Person>;
  xml listofChildren = input/<Person>/<Child>;
  foreach var person in listofPersons{
    xml childrenOfSinglePerson = person/<Child>;
  }
}

编译结果:

Compiling source
        test.bal
error: .::test.bal:5:20: incompatible types: expected 'xml',found '(xml|string)'

我正在使用Ballerina 1.2

解决方法

  1. 此错误是由于xml迭代器类型检查中的错误所致。 https://github.com/ballerina-platform/ballerina-lang/issues/24562

  2. 在程序迭代器执行期间不会返回string结果,因此您可以安全地将person强制转换为xml或进行类型保护(如类型测试)在下面。

function foo(xml input) returns boolean {
  xml listOfPersons = input/<Person>;
  xml listOfChildren = input/<Person>/<Child>;
  foreach var person in listOfPersons {
    if (person is xml) { // Workaround to only consider xml
        xml childrenOfSinglePerson = person/<Child>;
        return true;
    }
  }
}

或者,您也可以通过.forEach方法处理xml值。

listOfPersons.forEach(function (xml person) { xml c = person/<Child>; io:println(c); });