在Go中有阅读XML文档的一些通用方法吗?类似于C#中的XmlDocument或XDocument吗?
我发现的所有示例都显示了如何使用解编组功能将其读取到需要定义的对象中,但是这非常耗时,因为我需要定义很多我不打算使用的人员。
xml.Unmarshal(...)
另一种方法是仅使用以下方法转发阅读:
xml.NewDecoder(xmlFile)
在这里描述:http : //blog.davidsingleton.org/parsing-huge-xml-files-with-go/
我发现的所有示例都显示了如何使用解编组功能将其读取到需要定义的对象中,但是这非常耗时,因为我需要定义很多我不打算使用的人员。
然后,不要定义不使用的内容,而仅定义要使用的内容。您不必创建完全覆盖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中的以下信息:
您可以使用以下结构对这些所需的信息进行建模:
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]}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句