I am starting to use Go and have found that to parse an html or xml document does not have a powerful tool by itself (excuse my ignorance if not).
The fact is that I have the following map (I converted the xml to a map using github.com/clbanning/mxj). It's a XML and HTML Clover report.
What I want is access to the different values: XML pastebin
My code:
xmlFile, err := os.Open(dir + "\\clover.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
b, _ := ioutil.ReadAll(xmlFile)
defer xmlFile.Close()
fmt.Println("xmldata:", string(b))
// get all image tag values - []interface{}
mapvalue, merr := mxj.NewMapXml(b)
if merr != nil {
fmt.Println("merr:", merr.Error())
return
}
Even in the following way I can subdivide it:
sources, err := mapvalue.ValuesForKey("metrics")
if err != nil {
fmt.Println("err:", err.Error())
return
}
for i, src := range sources {
fmt.Println(i, src)
}
fmt.Println(sources[0])
It's that particular one I need. But now I can't access every one of the inner values.
map[-loc:459 -statements:71 -coveredmethods:14 -ncloc:307 -files:12 -conditionals:6 -coveredelements:45 -packages:8 -elements:110 -complexity:37 -classes:12 -coveredconditionals:1 -coveredstatements:30 -methods:33]
Is there an easier way to work with the XML and html I have in local?
I added the XML to map result: pastebin
GO has an xml parsing library https://golang.org/pkg/encoding/xml/
I have a runnable example here: https://play.golang.org/p/kVG3w4iu3Kl
package main
import (
"fmt"
"encoding/xml"
)
var rawXml = "<metrics coveredelements=\"45\" complexity=\"37\" loc=\"459\" methods=\"33\"/>"
type Metrics struct {
CoveredElements string `xml:"coveredelements,attr"`
Complexity string `xml:"complexity,attr"`
Loc string `xml:"loc,attr"`
Methods string `xml:"methods,attr"`
}
func main() {
data := &Metrics{}
xml.Unmarshal([]byte(rawXml), data)
fmt.Printf("%+v", data)
}
I think that you will find it much easier to work with structs.
I have found this utility to allow me to implement the necessary structures to parse the JSON answers (you can use a converter ). I hope you find it useful too:
https://mholt.github.io/json-to-go/
You can use a JSON/XML converter online like this: http://www.utilities-online.info/xmltojson/#.W1cSCNIzZPY.
For the rest I use the same what @Rossiar said in his comment.