如何使用 Xpath 和 Ballerina 在 XML 有效负载中搜索元素?



示例:如何使用芭蕾舞演员访问"城市"?

<h:People xmlns:h="http://www.test.com">
<h:name>Anne</h:name>
<h:address>
<h:street>Main</h:street>
<h:city>Miami</h:city>
</h:address>
<h:code>4</h:code>
</h:People>

我尝试使用 select 函数,但它没有向我返回任何内容。

payload.select("city")

我们可以使用相同的方法selectDescendants,但由于您的第二个示例没有 xml 元素的命名空间,我们必须使用空命名空间来查找子元素,如下所示。此外,selectDescendants返回一个包含所有匹配元素的 xml 序列。因此,要获得所需的 xml 元素,一种选择是使用正确的索引访问它。示例代码如下。

import ballerina/io;
function main (string... args) {
xml x = xml `<member>
<sourcedid>
<source>test1</source>
<id>1234.567</id>
</sourcedid>
<entity>
<sourcedid>
<source>test2</source>
<id>123</id>
</sourcedid>
<idtype>1</idtype>
</entity>
<entity>
<sourcedid>
<source>test</source>
<id>123</id>
</sourcedid>
<idtype>2</idtype>
</entity>
</member>`;
//Below would first find all the matched elements with "id" name and then get the first element
xml x1 = x.selectDescendants("{}id")[0];
io:println(x1);
}

若要在 xml 树中搜索子项,应使用selectDescendants方法。来自 xml 类型的文档;

<xml> selectDescendants(string qname) returns (xml)

在子项中递归搜索与合格元素匹配的元素 名称并返回包含所有这些内容的序列。不搜索 在匹配的结果中。

此外,还应使用元素的完全限定名称 (QName(。在您的示例中,城市元素的 QName{http://www.test.com}city

下面是一个示例代码。

import ballerina/io;
function main (string... args) {
xml payload = xml `<h:People xmlns:h="http://www.test.com">
<h:name>Anne</h:name>
<h:address>
<h:street>Main</h:street>
<h:city>Miami</h:city>
</h:address>
<h:code>4</h:code>
</h:People>`;
io:println(payload.selectDescendants("{http://www.test.com}city"));
}

您还可以利用芭蕾舞演员对 xml 命名空间的内置支持,并通过以下方式访问您的元素。

xmlns "http://www.test.com" as h;
io:println(payload.selectDescendants(h:city)); 

最新更新