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

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

Unmarshal an xml document with xmlns namespaces

问题

我想要解析一个类似以下结构的RDF文档:

  1. <?xml version="1.0" encoding="WINDOWS-1252"?>
  2. <rdf:RDF xmlns:owl = "http://www.w3.org/2002/07/owl#"
  3. xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  4. <!-- 其他XML元素 -->
  5. </rdf:RDF>

我使用以下类型进行解析:

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

以下是执行解析的代码片段:

  1. // 你需要导入 "github.com/rogpeppe/go-charset/charset"
  2. // 和 _ "github.com/rogpeppe/go-charset/data"
  3. dec := xml.NewDecoder(file)
  4. dec.CharsetReader = charset.NewReader
  5. var v wsdlDoc
  6. err = dec.Decode(&v)
  7. if err != nil {
  8. panic(err)
  9. }

当我运行这段代码时,会出现以下错误:

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

如何处理这种解析错误呢?

英文:

I want to unmarshal an RDF document that looks likes:

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

I'm using this type to unmarchal in:

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

the snippet of code to do this:

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

When I run the code the panic print this error:

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

How to handle this case of unmarshaling?

答案1

得分: 0

命名空间通过其URL表示,并通过空格与名称分隔,因此您的结构应该更像是这样的:

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

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

  1. type wsdlDoc struct {
  2. XMLName xml.Name `xml:&quot;http://www.w3.org/1999/02/22-rdf-syntax-ns# RDF&quot;`
  3. // ...
  4. }

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:

确定