doushang4274 2016-07-21 00: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 16: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

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面