问题描述
在 Go 中是否有一些通用的读取 XML 文档的方法?类似于 C# 中的 XmlDocument 或 XDocument?
Is there some general approach of reading XML document in Go? Something similar to XmlDocument or XDocument in C#?
我找到的所有示例都展示了如何使用解组功能将数据读取到我需要定义的对象中,但这非常耗时,因为我需要定义很多我不会使用的人员.
All the examples I found show how to read using unmarshaling functionality into the objects I need to define, but it's quite time consuming as I need to define a lot of staff that I'm not going to use.
xml.Unmarshal(...)
另一种方法是仅向前阅读使用:
Another approach is forward only reading using:
xml.NewDecoder(xmlFile)
此处描述:http://blog.davidsingleton.org/parsing-huge-xml-files-with-go/
推荐答案
然后不要定义你不会使用的东西,只定义你要使用的东西.您不必创建一个完美覆盖 XML 结构的 Go 模型.
Then don't define what you're not going to use, define only what you're going to use. You don't have to create a Go model that perfectly covers the XML structure.
假设您有一个这样的 XML:
Let's assume you have an XML like this:
<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 中的以下信息:
And let's assume you only need the following info out of this XML:
- id
- 关键词
- 博客名称
- 作者姓名
您可以使用以下结构对这些需要的信息进行建模:
You can model these wanted pieces of information with the following struct:
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"`
}
现在您可以使用以下代码仅解析这些信息:
And now you can parse only these information with the following code:
d := Data{}
if err := xml.Unmarshal([]byte(s), &d); err != nil {
panic(err)
}
fmt.Printf("%+v", d)
输出(在 Go Playground 上试试):
Output (try it on the Go Playground):
{Id:1234 Meta:{Keywords:xml,parsing,partial} Name:Partial XML parsing Authors:[Bob Alice]}
这篇关于Go 中的通用 XML 解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!