最近Erlang项目中有用到xml处理,简单研究了,主要查找erlang库中xmerl的初学文档(lib/xmerl-1.2.8/doc/html/xmerl_ug.html)。
并参考坚强2002的博客:http://www.cnblogs.com/me-sa/archive/2012/07/20/erlang_xml.html
废话不多说,上代码:
直接用官方给出的xml示例来处理(motorcycles.xml):
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE motorcycles SYSTEM "motorcycles.dtd"> <motorcycles> <bike year="2000" color="black"> <name> <manufacturer>Suzuki</manufacturer> <brandName>Suzuki VL 1500</brandName> <additionalName>Intruder</additionalName> </name> <engine>V-engine, 2-cylinders, 1500 cc</engine> <kind>custom</kind> <drive>cardan</drive> <accessories>Sissy bar, luggage carrier,V&H exhaust pipes</accessories> </bike> <date>2004.08.25</date> <bike year="1983" color="read pearl"> <name> <manufacturer>Yamaha</manufacturer> <brandName>XJ 400</brandName> </name> <engine>4 cylinder, 400 cc</engine> <kind>alround</kind> <drive>chain</drive> <comment>Good shape!</comment> </bike> </motorcycles>
如果xmerl_scan:file("motorcycles.xml"),报错,则请删除xml文件中DTD声明或者使用
xmerl_scan:file("motorcycles.xml", [{validation,false}]),
%% 取xml中bike属性year
get_attr_val() ->
{Result, _Rest} = xmerl_scan:file("motorcycles.xml"),
Years = xmerl_xpath:string("bike/@year", Result),
io:format("Format=====Years=====~p~n", [Years]),
lists:foldl(fun(K, Acc) ->
#xmlAttribute{value=Val} = K,
[{"year", Val}|Acc] end, [], Years).
执行结果:[{"year","1983"},{"year","2000"}]
%% 取xml中date值
get_xml_date() ->
{Result, _Rest} = xmerl_scan:file("motorcycles.xml"),
Date = xmerl_xpath:string("date", Result),
[#xmlElement{content = Content}] = Date,
[#xmlText{value = Val}] = Content,
{"date", Val}.
执行结果:{"date","2004.08.25"}
%% 取xml中name节点下manufacturer的值
get_xml_names() ->
{Result, _Rest} = xmerl_scan:file("motorcycles.xml"),
Bikes = xmerl_xpath:string("bike", Result),
NameVals = lists:foldl(fun(K, Acc) ->
Name = xmerl_xpath:string("name/manufacturer", K),
[#xmlElement{content = [#xmlText{value = Val}]}] = Name,
[{"manufacturer", Val}|Acc] end, [], Bikes),
lists:reverse(NameVals).
执行结果:[{"manufacturer","Suzuki"},{"manufacturer","Yamaha"}]
%% 转换xml
gen_xml_list() ->
XmlData = {bike, [{year,"2003"},{color,"black"},{condition,"new"}],
[{name, [{manufacturer,["Harley Davidsson"]},
{brandName,["XL1200C"]},
{additionalName,["Sportster"]}]},
{engine, ["V-engine, 2-cylinders, 1200 cc"]},
{kind,["custom"]},
{drive,["belt"]}]},
XmlLists = xmerl:export_simple([XmlData],xmerl_xml),
lists:flatten(XmlLists).
执行结果:"<?xml version=\"1.0\"?><bike year=\"2003\" color=\"black\" condition=\"new\">
<name><manufacturer>Harley Davidsson</manufacturer><brandName>XL1200C</brandName>
<additionalName>Sportster</additionalName></name><engine>V-engine, 2-cylinders, 1200 cc</engine>
<kind>custom</kind><drive>belt</drive></bike>"