问题描述
有人可以帮助我了解xml元素相对于foreach语句如何工作吗?
下面的示例代码显示了两种不同的方法来访问xml元素“ Child”。首先,直接访问所有“孩子”(第3行),然后仅访问foreach循环内的特定“人”的“孩子”(第5行)。
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
解决方法
-
此错误是由于xml迭代器类型检查中的错误所致。 https://github.com/ballerina-platform/ballerina-lang/issues/24562
-
在程序迭代器执行期间不会返回
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); });