Unmarshal命名空间XML标记 - Golang

问题描述:

我试图从.odt文档中提取元数据。Unmarshal命名空间XML标记 - Golang

的文件,其中包含XML被称为meta.xml

它具有这样的结构:

<?xml version="1.0" encoding="UTF-8"?> 
<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" office:version="1.2"> 
    <office:meta> 
     <meta:creation-date>2016-10-18T15:05:19.137453293</meta:creation-date> 
     <dc:title>Document</dc:title> 
     <dc:date>2017-01-17T00:59:04.731054728</dc:date> 
     <meta:document-statistic meta:page-count="1" meta:word-count="0" meta:character-count="0"/> 
    </office:meta> 
</office:document-meta> 

我使用xml.Unmarshal()encoding/xml包解析XML,并把结构领域内的值。

这是我使用的结构:

type Query struct { 
    CreationDate string `xml:""` 
    PageCount int `xml:""` 
    WordCount int `xml:""` 
    CharCount int `xml:""` 
} 

我从可用的文件理解的是,我可以用xml:"tag-name"类型的字段标签来获取XML标记的值,并xml:name,attr得到属性值。

但是,由于XML文件具有名称空间标签(例如meta:creation-date),所以我迄今试过的所有内容都将空字段留空。虽然,我可能做错了什么。

这是去游乐场内的整个程序: https://play.golang.org/p/n7C50l1gsV

+0

https://github.com/golang/go/issues/9519 - 最后的评论表明,只支持前缀的属性(不是元素)。 –

+0

我将如何去提取前缀属性?例如:'meta:word-count =“0”'或者它们也不可访问,因为标签是名称间隔的? – Anurope

+0

这是您的操场[代码](https://play.golang.org/p/YFO5jp70gN)的更新版本,可能会有所帮助。 –

你会发现,事情变得更加顺利,如果你的结构相当直接映射到XML。此代码应该让你开始:

package main 

import (
    "encoding/xml" 
    "fmt" 
) 

type Stats struct { 
    XMLName xml.Name 
    PageCount int `xml:"page-count,attr"` 
} 

type Meta struct { 
    XMLName xml.Name 
    Date string `xml:"creation-date"` 
    Title string `xml:"title"` 
    Stats Stats `xml:"document-statistic"` 
} 

type DocumentMeta struct { 
    XMLName xml.Name 
    Meta Meta `xml:"meta"` 
} 

var data = []byte(`<?xml version="1.0" encoding="UTF-8"?> 
<office:document-meta> 
    <office:meta> 
     <meta:creation-date>2016-10-18T15:05:19.137453293</meta:creation-date> 
     <dc:title>Document</dc:title> 
     <dc:date>2017-01-17T00:59:04.731054728</dc:date> 
     <meta:document-statistic meta:page-count="1" meta:word-count="0" meta:character-count="0"/> 
    </office:meta> 
</office:document-meta>`) 

func main() { 
    var dm DocumentMeta 
    xml.Unmarshal(data, &dm) 
    fmt.Println(dm) 
}