首页 > 解决方案 > 如何使用 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")

标签: ballerina

解决方案


要在 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"));
}

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

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

推荐阅读