小编典典

Go中的通用XML解析器

go

在Go中有一些读取XML文档的通用方法吗?类似于C#中的XmlDocument或XDocument吗?

我发现的所有示例都显示了如何使用解编组功能将其读取到需要定义的对象中,但是这非常耗时,因为我需要定义很多我不打算使用的人员。

xml.Unmarshal(...)

另一种方法是仅使用以下方法转发阅读:

xml.NewDecoder(xmlFile)

在这里描述:http :
//blog.davidsingleton.org/parsing-huge-xml-files-with-
go/


阅读 260

收藏
2020-07-02

共1个答案

小编典典

我发现的所有示例都显示了如何使用解编组功能将其读取到需要定义的对象中,但是这非常耗时,因为我需要定义很多我不打算使用的人员。

然后 ,不要 定义不使用的内容,而 定义要使用的内容。您不必创建完全覆盖XML结构的Go模型。

假设您有这样的XML:

<blog id="1234">
    <meta keywords="xml,parsing,partial" />
    <name>Partial XML parsing</name>
    <url>http://somehost.com/xml-blog</url>
    <entries count="2">
        <entry time="2016-01-19 08:40:00">
            <author>Bob</author>
            <content>First entry</content>
        </entry>
        <entry time="2016-01-19 08:30:00">
            <author>Alice</author>
            <content>Second entry</content>
        </entry>
    </entries>
</blog>

并假设您仅需要此XML中的以下信息:

  • ID
  • 关键字
  • 博客名称
  • 作者姓名

您可以使用以下结构对这些所需的信息进行建模:

type Data struct {
    Id   string `xml:"id,attr"`
    Meta struct {
        Keywords string `xml:"keywords,attr"`
    } `xml:"meta"`
    Name    string   `xml:"name"`
    Authors []string `xml:"entries>entry>author"`
}

现在,您可以使用以下代码仅解析这些信息:

d := Data{}
if err := xml.Unmarshal([]byte(s), &d); err != nil {
    panic(err)
}
fmt.Printf("%+v", d)

输出(在Go Playground上尝试):

{Id:1234 Meta:{Keywords:xml,parsing,partial} Name:Partial XML parsing Authors:[Bob Alice]}
2020-07-02