ballerina - 如何使用 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")
解决方案
要在 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));
推荐阅读
- c# - Converting to int
- ios - Mapbox iOS - 显示多个标注
- android - 删除某些字符后如何调整字符串中的索引?
- python - Python正则表达式提取处理器数量
- node.js - res 渲染不渲染 index.jade
- spring-boot - 具有现有 WSDL 的 Spring-WS SOAP 服务器未找到端点
- html - NSAttributedString 改变颜色和字体大小
- java - 安卓工作室上的LSH
- kotlin - 带有 RoundingMode.FLOOR 的 BigDecimal 给出了意想不到的结果
- r - 如何防止kable表丢失?