Arpitha Thorath
Arpitha Thorath

Reputation: 23

Unmarshalling xml tag with attribute

I am trying to extract some data from XML. The XML tag has an attribute and a value. I'm only interested in the value not attribute. Here's what I'm trying:

package main

import (
    "encoding/xml"
    "fmt"
)

type Data struct {
    Info Information `xml:"Reference"`
}

type Information struct {
    Uid  string `xml:"uid,attr"`
    Name string `xml:",chardata"`
}

func main() {
    str := `<?xml version="1.0" encoding="utf-8"?>
    <Reference uid="123">TestName</Reference>`

    var testData Data

    _ = xml.Unmarshal([]byte(str), &testData)

    fmt.Println("Name is ", testData.Info.Name)
    fmt.Println("uid is ", testData.Info.Uid)

    return
}

Upvotes: 2

Views: 56

Answers (1)

icza
icza

Reputation: 417402

Your source XML contains a single <Reference> element (and not an element inside another element), so model it with a simple struct (and not with a struct inside another struct):

type Information struct {
    Uid  string `xml:"uid,attr"`
    Name string `xml:",chardata"`
}

And unmarshal into a value of this struct:

var testData Information

err := xml.Unmarshal([]byte(str), &testData)
fmt.Println(err)

fmt.Println("Name is ", testData.Name)
fmt.Println("uid is ", testData.Uid)

This will output (try it on the Go Playground):

<nil>
Name is  TestName
uid is  123

Upvotes: 2

Related Questions