Skip to content

Instantly share code, notes, and snippets.

@jadeallenx
Forked from nkabardin/README
Created March 7, 2012 16:53
Show Gist options
  • Save jadeallenx/1994346 to your computer and use it in GitHub Desktop.
Save jadeallenx/1994346 to your computer and use it in GitHub Desktop.
Erlang xmerl-based simple xml parsing

Purpose

This module takes XML and turns it into a deep proplist. The original code was written by @wackum.

I modified it so it:

  • returns both attributes and the value instead of one or the other
  • doesn't ignore the top level tag
  • handles elements with empty content

Example xml

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
        <application id="test">
            <platform id="vk">
                <appId>123</appId>
                <secretKey>secret</secretKey>
                <packages>
                    <package id="vk0" price="100"  points="3" />
                    <package id="vk1" price="500"  points="20" />
                    <package id="vk2" price="1000" points="45" default="true" />
                    <package id="vk3" price="2500" points="130" />
                    <package id="vk4" price="5000" points="290" />
                </packages>
            </platform>
        </application>
</configuration>

Usage example

-module(t).
-export([test/0]).

test() ->
    XmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
    <configuration>
        <application id=\"test\">
            <platform id=\"vk\">
               <appId>123</appId>
               <secretKey>secret</secretKey>
               <packages>
                  <package id=\"vk0\" price=\"100\"  points=\"3\" />
                  <package id=\"vk1\" price=\"500\"  points=\"20\" />
                  <package id=\"vk2\" price=\"1000\" points=\"45\" default=\"true\" />
                  <package id=\"vk3\" price=\"2500\" points=\"130\" />
                  <package id=\"vk4\" price=\"5000\" points=\"290\" />
               </packages>
            </platform>
       </application>
    </configuration>",

    {Element, _} = xmerl_scan:string(XmlData),
    Rules = {configuration, [], 
        [{application, [{id, to_atom}], 
            [{platform, [{id, to_atom}], 
                [
                    {appId, [], to_binary},
                    {secretKey, [], to_binary},
                    {packages, [], [
                        {package, [{id, to_atom}, 
                                   {price, to_integer}, 
                                   {points, to_integer},
                                   {default, to_atom}], []}
                    ]}
                ]
            }]
    }]
    },
    beenzaxml:process_xml(Element, Rules).

Will return easy-to-use deep proplist:

[{configuration,
              [{application,
                   [{id,test},
                    {platform,
                        [{id,vk},
                         {appId,[{value,<<"123">>}]},
                         {secretKey,[{value,<<"secret">>}]},
                         {packages,
                             [{package,[{points,3},{price,100},{id,vk0}]},
                              {package,[{points,20},{price,500},{id,vk1}]},
                              {package,
                                  [{default,true},
                                   {points,45},
                                   {price,1000},
                                   {id,vk2}]},
                              {package,[{points,130},{price,2500},{id,vk3}]},
                              {package,
                                  [{points,290},
                                   {price,5000},
                                   {id,vk4}]}]}]}]}]}]

LICENSE

MIT license

Copyright (c) 2012 Mark Allen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

%% Turn XML into a deep proplist
%%
%% Original code by @wackum
%%
%% Copyright (C) 2012 by Mark Allen. All rights reserved.
%%
%% You may use this software under the MIT license as explained in the README
-module(beenzaxml).
-export([process_xml/2]).
-include_lib("xmerl/include/xmerl.hrl").
process_attributes(#xmlElement{attributes=Attributes}, Rules) ->
{_, AttributeRules, _} = Rules,
lists:foldl(fun (Attr, Acc) -> process_attribute(Attr, Acc, AttributeRules) end, [], Attributes).
process_attribute(#xmlAttribute{} = Attribute, State, Rules) ->
Name = Attribute#xmlAttribute.name,
Value = Attribute#xmlAttribute.value,
ProcessedValue = process_value(Value, proplists:get_value(Name, Rules)),
[{Name, ProcessedValue}|State].
process_value(Value, Fun) when is_function(Fun ,1) -> Fun(Value);
process_value(Value, to_atom) -> list_to_atom(Value);
process_value(Value, to_integer) -> list_to_integer(Value);
process_value(Value, to_binary) -> list_to_binary(Value);
process_value(Value, _) -> Value.
element_text_content(#xmlElement{}=Element) ->
Content = Element#xmlElement.content,
case Content of
[] ->
undefined;
_ ->
ContentHead = hd(Content),
ContentHead#xmlText.value
end.
process_xml(Element, Rules) ->
TagName = Element#xmlElement.name,
[{TagName, process_attributes(Element, Rules) ++ process_xml(Element, Rules, [])}].
process_xml(#xmlElement{name=TagName} = Element, {TagName, _AttributesRules, ChildrenRules}, State) when is_list(ChildrenRules) ->
[{ElTag, process_attributes(El, Rule) ++ process_xml(El, Rule, State)} ||
#xmlElement{name=ElTag} = El <- Element#xmlElement.content,
{RuleTag, _, _}=Rule <- ChildrenRules,
RuleTag==ElTag
] ++ State;
process_xml(#xmlElement{} = Element, Rule, _State) ->
{_TagName, _AttributeRules, ChildRules} = Rule,
[{content, process_value(element_text_content(Element), ChildRules)}];
process_xml(_, _, State) -> State.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment