Erlang的Xml解析常用函数:
xmerl_scan库:
string(Text::list()) -> {xmlElement(), Rest} Parse string containing an XML document,将字符串列表,解析成XML树
file(Filename::string()) -> {xmlElement(), Rest} Parse file containing an XML document
xmerl_xpath库:
string(Str, Doc) -> [docEntity()] | Scalar 根据XPath,从已经解析好的XML树中提取出节点
基础练习:
1> Xml="<?xml version='1.0' encoding='utf-8'?><root>123</root>".
"<?xml version='1.0' encoding='utf-8'?><root>123</root>"
2> {Doc,_}=xmerl_scan:string(Xml).
{{xmlElement,root,root,[],
{xmlNamespace,[],[]},
[],1,[],
[{xmlText,[{root,1}],1,[],"123",text}],
[],"/mnt/hgfs/work/myErlangWork/myErlang1/src",undeclared},
[]}
3> xmerl_xpath:string("/root",Doc).
[{xmlElement,root,root,[],
{xmlNamespace,[],[]},
[],1,[],
[{xmlText,[{root,1}],1,[],"123",text}],
[],"/mnt/hgfs/work/myErlangWork/myErlang1/src",undeclared}]
4> xmerl_xpath:string("/root/text()",Doc).
[{xmlText,[{root,1}],1,[],"123",text}]
举例:解析购物清单
shopping.xml
<?xml version="1.0" encoding="UTF-8"?>
<shopping>
<item name="bread" quantity="3" price="2.50">bread</item>
<item name="milk" quantity="2" price="3.50">milk</item>
</shopping>
xml_test.erl
-module(xml_test).
-include_lib("xmerl/include/xmerl.hrl").
-export([
test_xml/0,
test_xml_file/0
]).
%%读取xml列表为xmlElement,然后解析数据
test_xml() ->
Xml = "<shopping>
<item name=\"bread\" quantity=\"3\" price=\"2.50\">bread</item>
<item name=\"milk\" quantity=\"2\" price=\"3.50\">milk</item>
</shopping>",
{XmlDoc,_} = xmerl_scan:string(Xml),
get_total(XmlDoc),
get_item_text(XmlDoc).
%%Parse file containing an XML document,然后解析数据
test_xml_file() ->
{Doc,_} = xmerl_scan:file("shopping.xml",[{encoding,'utf-8'}]),
get_total(Doc),
get_item_text(Doc).
%%计算得到购物清单的总金额
get_total(XmlDoc) ->
Items = xmerl_xpath:string("/shopping/item",XmlDoc),
TotalPrice = lists:foldl(fun(Item,Total)->
[#xmlAttribute{value=PriceString}] = xmerl_xpath:string("/item/@price",Item),
[#xmlAttribute{value=QuantityString}] = xmerl_xpath:string("/item/@quantity",Item),
Price = list_to_float(PriceString),
Quantity = list_to_integer(QuantityString),
Total + Price * Quantity
end,
0,Items),
io:format("Price of shopping is $~.2f~n",[TotalPrice]),
TotalPrice.
%%获取购物清单上所有商品内容的列表,取item节点的text
get_item_text(XmlDoc) ->
Items = xmerl_xpath:string("/shopping/item",XmlDoc),
ItemList = lists:foldl(fun(Item,Result)->
[#xmlText{value=Value}] = xmerl_xpath:string("/item/text()",Item),
io:format("item is ~p~n",[Value]),
Result ++ [Value] %% 结果是["bread","milk"]
%% 此句如果改为Result ++ Value 结果就变成了"breadmilk"
end,
[],Items),
io:format("ItemList is ~p~n",[ItemList]),
ItemList.
执行:
1> c(xml_test).
{ok,xml_test}
2> xml_test:test_xml().
Price of shopping is $14.50
item is "bread"
item is "milk"
ItemList is ["bread","milk"]
["bread","milk"]
3> xml_test:test_xml_file().
Price of shopping is $14.50
item is "bread"
item is "milk"
ItemList is ["bread","milk"]
["bread","milk"]