Generic xml traversal.

Tim Fletcher <>
Sat Aug 21 13:48:37 CEST 2010


> Where Item is my main node that i want to get lists of.

In that case you could use XPath to select the list of 'Item'
elements, and then traverse each of those. For example:

    parse_file(Name) ->
      {XML, []} = xmerl_scan:file(Name),
      [parse(Item#xmlElement.content) || Item <- xmerl_xpath:string("//
something/Item", XML)].

    parse(Content) ->
      lists:foldl(fun (I, A) -> parse(I, A) end, [], Content).

    parse(#xmlElement{name=Name, content=[#xmlText{value=Value}]},
Acc) ->
      [{Name, Value} | Acc];
    parse(#xmlElement{name=Name, content=Content}, Acc) ->
      [{Name, parse(Content)} | Acc];
    parse(_, Acc) ->
      Acc.

That doesn't produce the exact output you posted, but it's reasonably
generic. Your example output uses strings for the tag names, but xmerl
uses atoms. Sometimes you might want atoms. Your example output
doesn't include the 'review' tag names; not sure whether that's a
mistake or whether you deliberately want to filter those out? Really
depends on what you're doing with the data.

Hope that helps anyway.

Tim


More information about the erlang-questions mailing list