doushang4274
2016-07-21 00:52
浏览 164

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题