[erlang-questions] how: xmerl export without "

Ulf Wiger <>
Thu Sep 19 10:31:20 CEST 2013


On 19 Sep 2013, at 09:34, Christoffer Vikström <> wrote:

> As far as i know the xml standard doesn't allow for unquoted attribute values, which is probably why xmerl outputs it that way. No idea if you can game xmerl to output non-standard xml though.
> 
> /Christoffer

The xmerl export requires only that the output is text, and one can always write an export callback that modifies an existing callback.

Here's one that seems to do roughly what Bengt wants (keeping the prolog unchanged, which may not matter, since the body is no longer proper XML):

-module(xml_wo_quotes).

-export(['#xml-inheritance#'/0]).

-export(['#element#'/5]).

'#xml-inheritance#'() -> [xmerl_xml].

'#element#'(Tag, Data, Attrs, Parents, E) ->
    strip(xmerl_xml:'#element#'(Tag, Data, Attrs, Parents, E)).

strip([["<", Tag|T]|Rest]) ->
    ["<", Tag, strip_(T) | Rest];
strip(["<", Tag|T]) ->
    ["<", Tag | strip_(T)];
strip([H]) when is_list(H) ->
    strip(H).

strip_(T) ->
    {Attrs, Rest} = take_attrs(T),
    [remove_quotes(Attrs), Rest].

take_attrs(L) ->
    take_attrs(L, []).

take_attrs([H|_] = L, Acc) when H==">"; H=="/>" ->
    {lists:reverse(Acc), L};
take_attrs([H|T], Acc) ->
    take_attrs(T, [H|Acc]).

remove_quotes(L) ->
    re:replace(L, "\\\"", "", [global]).


Example:

Eshell V5.9.2  (abort with ^G)
1> c(xml_wo_quotes).
{ok,xml_wo_quotes}
2> xmerl_scan:string("<?xml version=\"1.0\"?><foo a=\"1\" b=\"2\"><bar a=\"1\"/></foo>").
{{xmlElement,foo,foo,[],
             {xmlNamespace,[],[]},
             [],1,
             [{xmlAttribute,a,[],[],[],[{foo,1}],1,[],"1",false},
              {xmlAttribute,b,[],[],[],[{foo,1}],2,[],"2",false}],
             [{xmlElement,bar,bar,[],
                          {xmlNamespace,[],[]},
                          [{foo,1}],
                          1,
                          [{xmlAttribute,a,[],[],[],
                                         [{bar,1},{foo,...}],
                                         1,[],
                                         [...],...}],
                          [],[],"/Users/uwiger/src",undeclared}],
             [],"/Users/uwiger/src",undeclared},
 []}
3> xmerl:export([element(1,v(2))], xml_wo_quotes).
["<?xml version=\"1.0\"?>",
 [["<","foo",
   [[<<" a=">>,[],<<"1">>,[],<<" b=">>,[],<<"2">>,[]],[">"]],
   [["<","bar",[<<" a=">>,[],<<"1">>,[]],["/>"]]],
   ["</","foo",">"]]]]
4> io:fwrite("~s~n", [v(3)]).
<?xml version="1.0"?><foo a=1 b=2><bar a=1/></foo>
ok


BR,
Ulf

Ulf Wiger, Co-founder & Developer Advocate, Feuerlabs Inc.
http://feuerlabs.com





More information about the erlang-questions mailing list