doulu6160 2016-01-18 16:01
浏览 30
已采纳

Go中的通用XML解析器

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) 

Described here: http://blog.davidsingleton.org/parsing-huge-xml-files-with-go/

  • 写回答

2条回答 默认 最新

  • dqrfdl5708 2016-01-19 07:58
    关注

    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.

    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.

    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>
    

    And let's assume you only need the following info out of this XML:

    • id
    • keywords
    • blog name
    • authors names

    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)
    

    Output (try it on the Go Playground):

    {Id:1234 Meta:{Keywords:xml,parsing,partial} Name:Partial XML parsing Authors:[Bob Alice]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器