下面我们从CSV文件数据源动态创建一个XML:
shopping.csv 的内容:
bread,3,2.50 milk,2,3.50
要创建的XML如下:
<shopping> <item name="bread" quantity="3" price="2.50"/> <item name="milk" quantity="2" price="3.50"/> </shopping>
xml_test.xml的内容:
-module(xml_test). -include_lib("xmerl/include/xmerl.hrl"). -export([ test_create_xml/0,create_xml_with_csv/2 ]). test_create_xml() -> create_xml_with_csv("shopping.csv","shop.xml"). %%从CSV文件数据源动态创建一个XML,并写入一个shop.xml中 create_xml_with_csv(CSVFile,XmlFile) -> case file:read_file(CSVFile) of %%将整个文件读取到一个二进制数据中 {ok,Content} -> NewContent = create_xml(binary_to_list(Content)),file:write_file(XmlFile,NewContent); {error,Why} -> {error,Why} end. %%根据CSV的内容,动态地创建购物清单列表 create_xml(ShoppingList) -> Items = lists:map(fun(L) -> [Name,Quantity,Price] = string:tokens(L,","),{item,[{name,Name},{quantity,Quantity},{price,Price}],[]} end,string:tokens(ShoppingList,"\n")),xmerl:export_simple([{shopping,[],Items}],xmerl_xml).