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 iscsi服务无法访问,如何解决?
  • ¥15 感应式传感器制作的感应式讯响器
  • ¥15 如何使用SC92F8003固件库解析私有协议数据?
  • ¥15 如何在音频中嵌入字符串(水印)信息进行传递
  • ¥30 plc怎么以设计说明书申请软著
  • ¥15 硬盘识别不了,需要初始化,可我的数据怎么办
  • ¥15 lvm2被mask了,怎么unmask都没用(标签-ubuntu|关键词-apt)
  • ¥15 交叉注意力机制的残差问题
  • ¥15 微信小程序:渲染收货地址时页面不显示
  • ¥20 win7 64位DirectShow提示初始化失败如何解决?