无法使用Go获取XML属性值

问题描述 投票:0回答:1

我正在尝试使用Go编程语言解析EPUB元数据,我当前解析的XML非常简单:

<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
    <rootfiles>
        <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>

我想要属性

full-path
media-type
,Go 代码是:

package main                                                                                                                                                 

import (
    "fmt"
    "encoding/xml"
)

type RootFile struct {
    FullPath    string  `xml:"full-path,attr"`
    MediaType   string  `xml:"media-type,attr"`
}

func main() {
    xmlData := `
    <?xml version="1.0" encoding="UTF-8"?>
    <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
        <rootfiles>
            <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
       </rootfiles>
    </container>
    `

    var rootFile RootFile
    xml.Unmarshal([]byte(xmlData), &rootFile)
    fmt.Println(rootFile)
}

但我得到一个空结果:

{ }

我的代码有什么问题?

xml go parsing
1个回答
0
投票

我不相信 go 对这里使用的

container
标签有开箱即用的支持,所以我相信你只是因为没有完整地解析 XML 而受苦。

这些类型将是一个完整的解析:

type Container struct {
    Version string `xml:"version,attr"`
    Xmlns string `xml:"xmlns,attr"`
    RootFiles RootFiles `xml:"rootfiles"`
}

type RootFiles struct {
    Rootfile RootFile `xml:"rootfile"`
}

type RootFile struct {
    FullPath string `xml:"full-path,attr"`
    MediaType string `xml:"media-type,attr"`
}

但是您无需声明您不感兴趣的字段,例如

version
xmlns
。尽管如此,您仍然需要表达 xml 的整个树结构。这是完整的工作示例:

package main

import (
    "encoding/xml"
    "fmt"
)

type Container struct {
    Version string `xml:"version,attr"`
    Xmlns string `xml:"xmlns,attr"`
    RootFiles RootFiles `xml:"rootfiles"`
}

type RootFiles struct {
    RootFile RootFile `xml:"rootfile"`
}

type RootFile struct {
    FullPath string `xml:"full-path,attr"`
    MediaType string `xml:"media-type,attr"`
}

func main() {
    xmlData := `
    <?xml version="1.0" encoding="UTF-8"?>
    <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
        <rootfiles>
            <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
       </rootfiles>
    </container>
    `

    var rootFile Container
    err := xml.Unmarshal([]byte(xmlData), &rootFile)
    if err != nil {
        fmt.Printf("Something went wrong: %v", err)
    }
    fmt.Printf("RootFile->full-path %v\nRootFile->media-type %v\n",
        rootFile.RootFiles.RootFile.FullPath,
        rootFile.RootFiles.RootFile.MediaType)
}
© www.soinside.com 2019 - 2024. All rights reserved.