xml to json, parsing xml

296 views
Skip to first unread message

RS

unread,
Oct 7, 2021, 10:06:30 AM10/7/21
to golang-nuts
What is the best approach to convert xml to json? 
However I need above all to parse a very complex xml to see if related properties are existing. 
I thought maybe converting it to Json maybe make it easier. 


Don Caldwell

unread,
Apr 23, 2024, 12:29:15 PM4/23/24
to golang-nuts
Disclaimer - I am very new to golang.
I puzzled about this for a few days. After some struggle, I got a little program working that parses
arbitrary xml into a structure that json can understand. You can find it here:

burak serdar

unread,
Apr 23, 2024, 12:43:47 PM4/23/24
to Don Caldwell, golang-nuts
In general, you cannot convert xml to json. They have incompatible
models. XML elements are ordered similar to a JSON array, but in many
cases you want to map XML elements to JSON objects, which are
unordered name-value collections. Also, there is no JSON equivalent of
an XML attribute.

If you want to work with XML, either use xml marshaling, or find a
third-party DOM library.
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/90c0dd22-2d81-4393-b534-651a2376f386n%40googlegroups.com.

robert engels

unread,
Apr 23, 2024, 1:05:12 PM4/23/24
to burak serdar, Don Caldwell, golang-nuts
I don’t think that is true. There are multiple ways to model XML into json.

See this http://badgerfish.ning.com for one of them.

Don Caldwell

unread,
Apr 23, 2024, 1:19:34 PM4/23/24
to robert engels, burak serdar, golang-nuts
I agree. The link that I sent demonstrates one very simple way. Mapping XML with repetitive tag sets to JSON arrays, though, would take a bit of work meaning, I think, at least two passes.

D

Don Caldwell

unread,
Apr 23, 2024, 3:17:33 PM4/23/24
to robert engels, burak serdar, golang-nuts
Oops, I didn't look carefully at the json output of my little program. It does sometimes emit arrays. For example:

go build xmlparse.go

./xmlparse -url 'https://news.google.com/atom'


This produces what, for some part, represents acceptable json. The exceptions are the atom entries that would still require, I think, another pass to fix up the go structure unless someone applies a priori knowledge of the xml structure when building it.


D



D


D

twp...@gmail.com

unread,
Apr 24, 2024, 9:24:45 PM4/24/24
to golang-nuts
You can parse XML and JSON quickly with these tools:


They generate Go code that parses all the example XML and JSON files that you throw at them.

Regards,
Tom

Peter Galbavy

unread,
Apr 25, 2024, 2:56:11 AM4/25/24
to golang-nuts
I could really have used the go-xmlstruct a year ago :-) But, if I need to fill in more blanks I will try it!
Reply all
Reply to author
Forward
0 new messages