解组具有xmlns名称空间的xml文档

问题描述:

I want to unmarshal an RDF document that looks likes:

<?xml version="1.0" encoding="WINDOWS-1252"?>
<rdf:RDF  xmlns:owl       = "http://www.w3.org/2002/07/owl#"
   xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"

   <!-- other xml element -->
</rdf:RDF>

I'm using this type to unmarchal in:

type wsdlDoc struct {
    XMLName xml.Name `xml:"rdf:RDF"`
    Name    string   `xml:"grounding:hasAtomicProcessGrounding"`
}

the snippet of code to do this:

// you should import "github.com/rogpeppe/go-charset/charset"
// and _ "github.com/rogpeppe/go-charset/data"
dec := xml.NewDecoder(file)
dec.CharsetReader = charset.NewReader
var v wsdlDoc
err = dec.Decode(&v)
if err != nil {
    panic(err)
}

When I run the code the panic print this error:

panic: expected element type <rdf:RDF> but have <RDF>

How to handle this case of unmarshaling?

Namespaces are denoted by their URL and separated from names by a space, so your struct should be more like

type wsdlDoc struct {
    XMLName xml.Name `xml:"http://www.w3.org/1999/02/22-rdf-syntax-ns# RDF"`
    // ...
}

Playground example: http://play.golang.org/p/tYVm2h6cIm.