Erlang的Xml解析

前端之家收集整理的这篇文章主要介绍了Erlang的Xml解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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. 1> Xml="<?xml version='1.0' encoding='utf-8'?><root>123</root>".
  2. "<?xml version='1.0' encoding='utf-8'?><root>123</root>"
  3. 2> {Doc,_}=xmerl_scan:string(Xml).
  4. {{xmlElement,root,[],{xmlNamespace,[]},1,[{xmlText,[{root,1}],"123",text}],"/mnt/hgfs/work/myErlangWork/myErlang1/src",undeclared},[]}
  5. 3> xmerl_xpath:string("/root",Doc).
  6. [{xmlElement,undeclared}]
  7. 4> xmerl_xpath:string("/root/text()",Doc).
  8. [{xmlText,text}]

举例:解析购物清单
shopping.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <shopping>
  3. <item name="bread" quantity="3" price="2.50">bread</item>
  4. <item name="milk" quantity="2" price="3.50">milk</item>
  5. </shopping>

xml_test.erl
  1. -module(xml_test).
  2. -include_lib("xmerl/include/xmerl.hrl").
  3. -export([
  4. test_xml/0,test_xml_file/0
  5. ]).
  6.  
  7. %%读取xml列表为xmlElement,然后解析数据
  8. test_xml() ->
  9. Xml = "<shopping>
  10. <item name=\"bread\" quantity=\"3\" price=\"2.50\">bread</item>
  11. <item name=\"milk\" quantity=\"2\" price=\"3.50\">milk</item>
  12. </shopping>",{XmlDoc,_} = xmerl_scan:string(Xml),get_total(XmlDoc),get_item_text(XmlDoc).
  13.  
  14. %%Parse file containing an XML document,然后解析数据
  15. test_xml_file() ->
  16. {Doc,_} = xmerl_scan:file("shopping.xml",[{encoding,'utf-8'}]),get_total(Doc),get_item_text(Doc).
  17.  
  18. %%计算得到购物清单的总金额
  19. get_total(XmlDoc) ->
  20. Items = xmerl_xpath:string("/shopping/item",XmlDoc),TotalPrice = lists:foldl(fun(Item,Total)->
  21. [#xmlAttribute{value=PriceString}] = xmerl_xpath:string("/item/@price",Item),[#xmlAttribute{value=QuantityString}] = xmerl_xpath:string("/item/@quantity",Price = list_to_float(PriceString),Quantity = list_to_integer(QuantityString),Total + Price * Quantity
  22. end,Items),io:format("Price of shopping is $~.2f~n",[TotalPrice]),TotalPrice.
  23.  
  24. %%获取购物清单上所有商品内容的列表,取item节点的text
  25. get_item_text(XmlDoc) ->
  26. Items = xmerl_xpath:string("/shopping/item",ItemList = lists:foldl(fun(Item,Result)->
  27. [#xmlText{value=Value}] = xmerl_xpath:string("/item/text()",io:format("item is ~p~n",[Value]),Result ++ [Value] %% 结果是["bread","milk"]
  28. %% 此句如果改为Result ++ Value 结果就变成了"breadmilk"
  29. end,io:format("ItemList is ~p~n",[ItemList]),ItemList.

执行:
  1. 1> c(xml_test).
  2. {ok,xml_test}
  3. 2> xml_test:test_xml().
  4. Price of shopping is $14.50
  5. item is "bread"
  6. item is "milk"
  7. ItemList is ["bread","milk"]
  8. ["bread","milk"]
  9. 3> xml_test:test_xml_file().
  10. Price of shopping is $14.50
  11. item is "bread"
  12. item is "milk"
  13. ItemList is ["bread","milk"]

猜你在找的XML相关文章