Skip to content

Instantly share code, notes, and snippets.

@Vesnica
Last active December 11, 2015 05:58
Show Gist options
  • Save Vesnica/4555360 to your computer and use it in GitHub Desktop.
Save Vesnica/4555360 to your computer and use it in GitHub Desktop.
Simple Erlang XML Parser
[
{xml, "F:/broadband/cwmp/tr-196-2-0-full.xml"},
{ignore_names, [description, bibliography]},
{ignore_attributes, ['xmlns:dm', 'xmlns:dmr', 'xmlns:xsi', 'xsi:schemaLocation', spec, file, 'dmr:version']}
].
-module(xml).
-author("Wisher").
-email("hustitecwisher@gmail.com").
-export([file/1]).
-include_lib("xmerl/include/xmerl.hrl").
file(Conf) ->
{ok, Config} = file:script(Conf),
XmlFile = proplists:get_value(xml, Config),
IgnoreNames = proplists:get_value(ignore_names, Config),
IgnoreAttrs = proplists:get_value(ignore_attributes, Config),
{Element, _} = xmerl_scan:file(XmlFile),
xmlElement(Element, IgnoreNames, IgnoreAttrs).
xmlElement(#xmlElement{name = Name, attributes = Attr, content = C}, IL, AIL) ->
case lists:member(Name, IL) of
true ->
ignore;
false ->
{Name, xmlAttribute(Attr, AIL, []), content(C, IL, AIL, [])}
end.
content([], _, _, State) ->
lists:reverse(State);
content([#xmlElement{} = C | Rest], IL, AIL, State) ->
case xmlElement(C, IL, AIL) of
ignore ->
content(Rest, IL, AIL, State);
V ->
content(Rest, IL, AIL, [V | State])
end;
content([#xmlText{} = C | Rest], IL, AIL, State) ->
case xmlText(C) of
ignore ->
content(Rest, IL, AIL, State);
V ->
content(Rest, IL, AIL, [V | State])
end;
content([_ | Rest], IL, AIL, State) ->
content(Rest, IL, AIL, State).
xmlAttribute([], _, State) ->
lists:reverse(State);
xmlAttribute([#xmlAttribute{name = Name, value = Value} | Attr], AIL, State) ->
case lists:member(Name, AIL) of
true ->
xmlAttribute(Attr, AIL, State);
false ->
xmlAttribute(Attr, AIL, [{Name, Value} | State])
end.
xmlText(#xmlText{type = Type, value = Value}) ->
case is_list(Value) andalso hd(Value) =:= 10 of
true ->
ignore;
false ->
{Type, Value}
end.
@Vesnica
Copy link
Author

Vesnica commented Jan 17, 2013

Usage:
{RootName, RootAttributesList, ContentDeepList} = xml:file("test.xml").

Desc:
This parser only process the xmlElement, xmlAttribute and xmlText node.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment