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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助