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

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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装