IanZG
IanZG

Reputation: 57

Golang - How to extract part of an XML file as a string?

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

Upvotes: 3

Views: 9532

Answers (2)

Alper
Alper

Reputation: 13220

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)
}

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

Output:

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

Upvotes: 10

Dean Elbaz
Dean Elbaz

Reputation: 2450

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

Upvotes: 2

Related Questions