Go XML chardata prints empty line

Viewed 126

I have a basic xml field which looks like this <cpe test="123">cpe:/a:openbsd:openssh:5.3p1</cpe> and I want to unmarshal it using Go. I create the object and while it normally unmarshals and prints the test attribute, the content inside the brackets is always printed as empty.

package main

import (
    "fmt"
    "encoding/xml"
)

type Cpe struct {
    XMLName xml.Name `xml:"cpe"`
    Value   string   `xml:"chardata"`
    Res string   `xml:"test,attr"`
}

func main() {

    var inputXML = `<cpe test="123">cpe:/a:openbsd:openssh:5.3p1</cpe>`

    byteValue := []byte(inputXML)
    
    // Create the onject
    var cpe Cpe
    
    // Unmarshal the xml using the Address object
    xml.Unmarshal(byteValue, &cpe)
    
    // prints the Res and Address Value
    fmt.Println(cpe.Res)
    fmt.Println(cpe.Value)  
}

The output of those things are 123 and nothing. By googling I find out that I can use innerXML instead of chardata, which had the same result.

Playground: https://play.golang.org/p/7eyoXjnOlS4

1 Answers

chardata is an option and not an XML tag or attribute name, so you have to put a comma before it if you just specify an option:

Value   string   `xml:",chardata"`

Also do check errors:

// Unmarshal the xml using the Address object
err := xml.Unmarshal(byteValue, &cpe)
fmt.Println("err:", err)

// prints the Res and Address Value
fmt.Println("attribute:", cpe.Res)
fmt.Println("chardata:", cpe.Value)

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

err: <nil>
attribute: 123
chardata: cpe:/a:openbsd:openssh:5.3p1
Related