英文:
Unmarshal an xml document with xmlns namespaces
问题
我想要解析一个类似以下结构的RDF文档:
<?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#"
<!-- 其他XML元素 -->
</rdf:RDF>
我使用以下类型进行解析:
type wsdlDoc struct {
XMLName xml.Name `xml:"rdf:RDF"`
Name string `xml:"grounding:hasAtomicProcessGrounding"`
}
以下是执行解析的代码片段:
// 你需要导入 "github.com/rogpeppe/go-charset/charset"
// 和 _ "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)
}
当我运行这段代码时,会出现以下错误:
panic: expected element type <rdf:RDF> but have <RDF>
如何处理这种解析错误呢?
英文:
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?
答案1
得分: 0
命名空间通过其URL表示,并通过空格与名称分隔,因此您的结构应该更像是这样的:
type wsdlDoc struct {
XMLName xml.Name `xml:"http://www.w3.org/1999/02/22-rdf-syntax-ns# RDF"`
// ...
}
Playground示例:http://play.golang.org/p/tYVm2h6cIm。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论