douzao9845
2014-12-17 14:14
浏览 125

Golang-如何将XML文件的一部分提取为字符串?

My XML looks something like this:

<a>
  <b>
    <c>
      <d>TEXT</d>
   </c>
  </b>
</a>

I know how to separate this code via the xml.Unmarshal function, but is there any way to perform the Unmarshal action only to a certain depth? For example, if I wanted to get a string that says "TEXT" and pass that into another function? I tried giving a child charset object, but it still tries to parse the rest of the XML...

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongpao1873 2014-12-17 14:57
    已采纳

    I think this is what you are asking (consider your comment as well).

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    func main() {
        type Result struct {
            Value  string `xml:"b>c>d"`
        }
        v := Result{"none"}
    
        data := `
            <a>
                <b>
                    <c>
                        <d>TEXT</d>             
                    </c>
                </b>
            </a>
        `
        err := xml.Unmarshal([]byte(data), &v)
        if err != nil {
            fmt.Printf("error: %v", err)
            return
        }
    
        fmt.Printf("Value: %v
    ", v.Value)
    }
    

    Output:

    Value: TEXT
    

    UPDATE: after lanZG's comment

    func main() {
        type InnerResult struct {
            Value string `xml:",innerxml"`
        }
    
        type Result struct {
            B InnerResult `xml:"b"`
        }
        v := Result{InnerResult{"none"}}
    
        data := `
            <a>
                <b>
                    <c>
                        <d>TEXT</d>             
                    </c>
                </b>
            </a>
        `
        err := xml.Unmarshal([]byte(data), &v)
        if err != nil {
            fmt.Printf("error: %v", err)
            return
        }
    
        fmt.Printf("Value: %v
    ", v.B.Value)
    }
    

    Output:

    Value: 
                    <c>
                        <d>TEXT</d>             
                    </c>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dotwc62080 2014-12-17 14:36

    You can use nested xml tags to make it easier with xml.Unmarshal

    here is how it would work: http://play.golang.org/p/XtCX7Dh45u

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题