Parse XML with nested elements

1,574 views
Skip to first unread message

Vladimir Mihailenco

unread,
Dec 29, 2012, 5:59:26 AM12/29/12
to golan...@googlegroups.com
Hi,

I have to parse XML like this:

<entry>
  <vars>
    <var key="foo">bar</var>
    <var key="foo2"><var key="hello">world</var></var>
  </vars>
</entry>

into this

{
  "foo": "bar",
  "foo2": {"hello": "world"}
}

Any ideas how to do this? I am thinking about using http://golang.org/pkg/encoding/xml/#Decoder.Token to parse this into map[string]interface{} .

Also what is the simplest way to get XML between <vars></vars>? I try this: http://play.golang.org/p/NKsPStD2Om , but it fails.

Dmitri Melnikov

unread,
Dec 29, 2012, 9:29:03 PM12/29/12
to golan...@googlegroups.com
One approach would be to make xml.Unmarshal() recursively build a tree of vars and then convert that tree to a map: http://play.golang.org/p/eA4_caHLyk

As for the second question, the code fails because the "innerxml" tag doesn't work when a node name is specified (same with "chardata", "comment" and "any"). You can see the code that checks for this here: http://golang.org/src/pkg/encoding/xml/typeinfo.go#L140.
To avoid that problem, specify a separate struct to hold the raw content like this: http://play.golang.org/p/tp0gkrAunb

Philipp Schumann

unread,
Jan 2, 2013, 6:47:03 AM1/2/13
to golan...@googlegroups.com
I can highly recommend:

Reply all
Reply to author
Forward
0 new messages