doushang4274 2016-07-20 16:52
浏览 167
已采纳

Golang:使用xml.decode从xml获取内部xml

I have simple XML like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
  <nexgen_audio_export>
    <audio ID="id_1667331726_30393658">
      <type>Song</type>
      <status>Playing</status>
      <played_time>09:41:18</played_time>
      <composer>Frederic Delius</composer>
      <title>Violin Sonata No.1</title>
      <artist>Tasmin Little, violin; Piers Lane, piano</artist>
      <comments>
         <p>Comment line1</p>
         <p>Comment <b>line2</b></p>
         <p>Comment line3</p>
      </comments>
    </audio>
  </nexgen_audio_export>

How can I get inner XML from xml:"nexgen_audio_export>audio>comments" with all tags (<p>, <b>, etc) using xml.decode?

Thank you, AP

  • 写回答

1条回答 默认 最新

  • dousi2013 2016-07-21 08:33
    关注

    From https://golang.org/pkg/encoding/xml/#Unmarshal:

    If the struct has a field of type []byte or string with tag ",innerxml", Unmarshal accumulates the raw XML nested inside the element in that field.

    You can just use the struct tag ",innerxml" to a field of type string or []byte that's inside the element you're trying to extract XML from. You'll need to use a sub-struct. Also note that the selection query of the XML library starts at the first element (It's quite strange). So you can't start the tag with nexgen_audio_export>, but rather go straight to audio>.

    Here's working example code:

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    // Encoding had to be changed to UTF-8
    var input = []byte(`<?xml version="1.0" encoding="UTF-8"?>
      <nexgen_audio_export>
        <audio ID="id_1667331726_30393658">
          <type>Song</type>
          <status>Playing</status>
          <played_time>09:41:18</played_time>
          <composer>Frederic Delius</composer>
          <title>Violin Sonata No.1</title>
          <artist>Tasmin Little, violin; Piers Lane, piano</artist>
          <comments>
             <p>Comment line1</p>
             <p>Comment <b>line2</b></p>
             <p>Comment line3</p>
          </comments>
        </audio>
      </nexgen_audio_export>`)
    
    type audio struct {
        Comments struct {
            InnerXML string `xml:",innerxml"`
        } `xml:"audio>comments"`
    }
    
    func main() {
        var a audio
        err := xml.Unmarshal(input, &a)
        if err != nil {
            panic(err)
        }
    
        fmt.Println(a.Comments.InnerXML)
    }
    

    Playground link: https://play.golang.org/p/LAL2V0zExc

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部