Golang-如何将XML文件的一部分提取为字符串? [英] Golang - How to extract part of an XML file as a string?

查看:40
本文介绍了Golang-如何将XML文件的一部分提取为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的XML看起来像这样:

My XML looks something like this:

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

我知道如何通过xml.Unmarshal函数分隔此代码,但是有什么方法可以仅在一定深度下执行Unmarshal动作吗?例如,如果我想获取一个表示"TEXT"的字符串并将其传递给另一个函数?我尝试给一个子charset对象,但是它仍然尝试解析XML的其余部分...

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...

推荐答案

我认为这就是您要问的(也请考虑您的评论).

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\n", v.Value)
}

输出:

Value: TEXT

更新:在lanZG发表评论后

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\n", v.B.Value)
}

输出:

Value: 
                <c>
                    <d>TEXT</d>             
                </c>

这篇关于Golang-如何将XML文件的一部分提取为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆