【发布时间】:2015-09-15 06:32:51
【问题描述】:
我正在尝试使用标准编码/xml 包在 Go 中处理具有复杂结构的 XML 文件,更改几个节点的值并保存备用文件。例如:
<description>
<title-info>
<genre>Comedy</genre>
<author>
<first-name>Kevin</first-name>
<last-name>Smith</last-name>
</author>
<movie-title>Clerks</movie-title>
<annotation>
<p>!!!</p>
</annotation>
<keywords>comedy,jay,bob</keywords>
<date></date>
</description>
</title-info>
还有更多领域。我想更改节点:
<author>
<first-name>Kevin</first-name>
<last-name>Smith</last-name>
</author>
到
<author>
<first-name>K.</first-name>
<middle-name>Patrick</middle-name>
<last-name>Smith</last-name>
</author>
但是,由于文件很大并且使用超过 50 个标签,我真的不想描述完整的结构来解组它们,所以我有
type Result struct {
Title string `xml:"description>title-info>movie-title"`
Authors []Author `xml:"description>title-info>author"`
}
type Author struct {
Fname string `xml:"first-name"`
Mname string `xml:"middle-name"`
Lname string `xml:"last-name"`
}
对于我需要处理的字段,但不知道如何保持文件的其余部分不受影响。看起来我需要使用 xml.decode 来选择我需要更改的节点(如http://blog.davidsingleton.org/parsing-huge-xml-files-with-go/ 帖子),同时将不需要的令牌跳过到 xml.encode,但我无法将此难题转换为某些代码。
【问题讨论】:
-
我想说你可以试试看 XSLT。可能是this?不幸的是,这引入了对
libxml2的依赖。
标签: xml go encode unmarshalling