在 Go 中解析 XML

Ela*_*hmi 2 xml go

我有以下 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>
Run Code Online (Sandbox Code Playgroud)

我试图将它解组到这个结构:

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"`
}
Run Code Online (Sandbox Code Playgroud)

没有抛出错误,但结果结构的值是空的。我尝试遵循我在网上找到的几个例子,但我是 Go 的新手,所以我可能会遗漏一些明显的东西。

Ain*_*r-G 5

首先,您的文档声明它是用 UTF-16 编码的,这意味着您需要设置解码器的CharsetReader,或者删除它并将文档解释为 UTF-8。

其次,您xsi:type,attr应该使用命名空间 URL,所以它是http://www.w3.org/2001/XMLSchema-instance type,attr.

考虑到这两点,你的事情就行了:https : //play.golang.org/p/Nu3wyEQ_dO