Go 中的通用 XML 解析器

Ark*_*dyB 2 xml go xml-parsing

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

我找到的所有示例都展示了如何使用解组功能将解组功能读取到我需要定义的对象中,但这非常耗时,因为我需要定义很多我不会使用的人员。

xml.Unmarshal(...)
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用以下方法仅向前阅读:

xml.NewDecoder(xmlFile) 
Run Code Online (Sandbox Code Playgroud)

此处描述:http : //blog.davidsingleton.org/parsing-huge-xml-files-with-go/

icz*_*cza 5

我找到的所有示例都展示了如何使用解组功能将解组功能读取到我需要定义的对象中,但这非常耗时,因为我需要定义很多我不会使用的人员。

然后不要定义你不会使用的东西,定义你将使用的东西。您不必创建完全覆盖 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>
Run Code Online (Sandbox Code Playgroud)

假设您只需要此 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"`
}
Run Code Online (Sandbox Code Playgroud)

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

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

输出(在Go Playground上试试):

{Id:1234 Meta:{Keywords:xml,parsing,partial} Name:Partial XML parsing Authors:[Bob Alice]}
Run Code Online (Sandbox Code Playgroud)