解析带有xmlns命名空间的XML文档。

huangapple go评论90阅读模式
英文:

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:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;WINDOWS-1252&quot;?&gt;
&lt;rdf:RDF  xmlns:owl       = &quot;http://www.w3.org/2002/07/owl#&quot;
   xmlns:rdf = &quot;http://www.w3.org/1999/02/22-rdf-syntax-ns#&quot;
   
   &lt;!-- other xml element --&gt;
&lt;/rdf:RDF&gt;

I'm using this type to unmarchal in:

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

the snippet of code to do this:

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

When I run the code the panic print this error:

panic: expected element type &lt;rdf:RDF&gt; but have &lt;RDF&gt;

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:&quot;http://www.w3.org/1999/02/22-rdf-syntax-ns# RDF&quot;`
	// ...
}

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

huangapple
  • 本文由 发表于 2015年11月12日 01:45:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/33656596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定