Some simple examples of using Erlang’s XPath implementation

本文介绍使用Erlang的xmerl库进行XPath查询的方法。通过实例演示如何解析XML文档,选择节点并提取特定元素内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址 [url]http://www.lshift.net/blog/2008/01/31/some-simple-examples-of-using-erlangs-xpath-implementation[/url]

[color=red]
这篇文章很好的介绍了xmerl_xpath 这个很方便的东西, 而在官方的文档里, 一笔带过, 让人不识宝,我把它挖掘出来,有兴趣的同学折腾折腾...[/color]


We’ve been investigating the possibility of an XPath-based routing extension to RabbitMQ, where XPath would be used as binding patterns, and the message structure would be exposed as XML infoset. As part of this work, we’ve been looking at Erlang’s XPath implementation that comes as part of the built-in xmerl library.

Here are a couple of examples of Erlang’s XPath in action. First, let’s parse a document to be queried:

{ParsedDocumentRootElement, _RemainingText = ""} =
xmerl_scan:string("<foo>" ++
"<myelement myattribute=\"red\">x</myelement>" ++
"<myelement myattribute=\"blue\">x</myelement>" ++
"<myelement myattribute=\"blue\">y</myelement>" ++
"</foo>").

(We could have used xmerl_scan:file to read from an external file, instead of xmerl_scan:string, if we’d wanted to.)

Next, let’s retrieve the contents of every myelement node that contains text exactly matching “x”:

69> xmerl_xpath:string("//myelement[. = 'x']/text()”,
ParsedDocumentRootElement).
[#xmlText{parents = [{myelement,1},{foo,1}],
pos = 1,
language = [],
value = “x”,
type = text},
#xmlText{parents = [{myelement,2},{foo,1}],
pos = 1,
language = [],
value = “x”,
type = text}]

Notice that it’s returned two XML text nodes, and that the “parents” elements differ, corresponding to the different paths through the source document to the matching nodes.

Next, let’s search for all myelements that have a myattribute containing the string “red”:

72> xmerl_xpath:string("//myelement[@myattribute='red']“,
ParsedDocumentRootElement).
[#xmlElement{
name = myelement,
expanded_name = myelement,
nsinfo = [],
namespace = #xmlNamespace{default = [],nodes = []},
parents = [{foo,1}],
pos = 1,
attributes =
[#xmlAttribute{
name = myattribute,
expanded_name = [],
nsinfo = [],
namespace = [],
parents = [],
pos = 1,
language = [],
value = “red”,
normalized = false}],
content =
[#xmlText{
parents = [{myelement,1},{foo,1}],
pos = 1,
language = [],
value = “x”,
type = text}],
language = [],
xmlbase = “/localhome/tonyg”,
elementdef = undeclared}]

This time, there’s only the one match. Finally, a query that no nodes satisfy:

75> xmerl_xpath:string("//myelement[@myattribute='red' and . = 'y']“,
ParsedDocumentRootElement).
[]

If we had replaced the 'y' with 'x', we’d have retrieved a non-empty nodeset.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值