英文:
XML unmarshal not working on First element
问题
我正在尝试解析XML。
type XMLCSFP struct {
Version string `xml:"version,attr"`
}
type XMLCS struct {
Container XMLCSFP `xml:"container"`
}
v2 := XMLCS{}
data := `
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
`
err = xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Println(v)
它没有显示版本1.0
。结构体的值是nil
。
但是当我用div
容器包装XML时,它正常工作。
data := `
<div>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
</div>
第一个示例有什么问题?谢谢!
英文:
I'm trying to unmarshal XML.
type XMLCSFP struct {
Version string `xml:"version,attr"`
}
type XMLCS struct {
Container XMLCSFP `xml:"container"`
}
v2 := XMLCS{}
data := `
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
`
err = xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Println(v)
It's not showing me the version 1.0
. The struct value is nil
But when I wrap the xml with div
container. It's working fine.
data := `
<div>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
</div>
`
What is the problem with the first one? Thanks!
答案1
得分: 2
XML的根元素将被解组为提供的指针类型。在你的情况下,这是XMLCS
。由于version
是根元素的属性,如果存在,它将进入XMLCS
中名为version
的字段。
所以,将你的结构体修改如下可以解决这个问题:
type XMLCS struct {
XMLName string `xml:"container"`
Version string `xml:"version,attr"`
}
详细了解XML如何映射到结构体的信息,请阅读Marshal的文档。
英文:
The root element of XML is unmarshalled into the type of the pointer provided. In your case, this is XMLCS
. Since version
is an attribute of the root element, it will go into a field named version
in XMLCS
, if present.
So changing your struct as below should fix the problem,
type XMLCS struct {
XMLName string `xml:"container"`
Version string `xml:"version,attr"`
}
Read the documentation of Marshal for details on how XML is mapped to structs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论