douzao9845 2014-12-17 14:14 采纳率: 0%
浏览 138
已采纳

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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题