Erlang动态创建XML

下面我们从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,并将生成的XML写入shop.xml文件中:
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).



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值