Elad Lachmi
Elad Lachmi

Reputation: 10561

Parse XML in Go

I have the following XML:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfAnyType xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <anyType xsi:type="xsd:dateTime">2016-09-14T13:58:30Z</anyType>
    <anyType xsi:type="xsd:decimal">1.2</anyType>
</ArrayOfAnyType>

I'm trying to unmarshal it to this struct:

type Value struct {
    XMLName xml.Name `xml:"ArrayOfAnyType"`
    Data []Data `xml:"anyType"`
}

type Data struct {
    Key string `xml:"xsi:type,attr"`
    Value string `xml:",chardata"`
}

There is no error thrown, but the values of the resulting struct are empty. I tried following several examples I found online, but I'm new to Go, so I might be missing something obvious.

Upvotes: 2

Views: 994

Answers (1)

Ainar-G
Ainar-G

Reputation: 36199

Firstly, your document states that it's encoded in UTF-16, which means you need to either set decoder's CharsetReader, or remove it and interpret the document as UTF-8.

Secondly, your xsi:type,attr should use the namespace URL, so it's http://www.w3.org/2001/XMLSchema-instance type,attr.

With those two in mind, your thing works: https://play.golang.org/p/Nu3wyEQ_dO.

Upvotes: 5

Related Questions