【问题标题】:Golang XML processingGolang XML 处理
【发布时间】: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


【解决方案1】:

你只使用标准库有限制吗?

如果不是,我推荐 etree (https://github.com/beevik/etree),它将 DOM 置于标准库的 XML 处理之上。它具有用于选择节点的基本 xpath 语法,一旦拥有它们,您就可以轻松地对其进行编辑。

【讨论】:

    猜你喜欢
    • 2016-04-10
    • 2015-03-29
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 2023-02-21
    相关资源
    最近更新 更多