我已经开始解析xml文件。但是我在整理以下元素时遇到了麻烦:
<Example>
<xhtml:p>
Some paragraph text
</xhtml:p>
<xhtml:div>
Some div text
</xhtml:div>
</Example>
我想在xhtml:p和xhtml:div中提取文本我写了下面的代码
package main
import (
"fmt"
"encoding/xml"
)
type Example struct{
XMLName xml.Name `xml:"Example"`
Paragraphs []string `xml:"xhtml:p"`
Divs []string `xml:"xhtml:div"`
}
func main() {
x:= []byte(`
<Example>
<pr>hello pr</pr>
<xhtml:p>
Some paragraph text
</xhtml:p>
<xhtml:div>
Some div text
</xhtml:div>
</Example>
`)
var a Example
xml.Unmarshal(x,&a)
fmt.Println(a)
}
但是,当我打印a
时,我得到了Paragraphs
和Divs
的空 slice 。有什么想法我做错了吗?
最佳答案
从struct标记中删除标记 namespace ,它将起作用:
type Example struct {
XMLName xml.Name `xml:"Example"`
Paragraphs []string `xml:"p"`
Divs []string `xml:"div"`
}
进行此更改后,输出为(在Go Playground上尝试):{{ Example} [
Some paragraph text
] [
Some div text
]}
如果确实要指定 namespace ,则必须将其添加到带有空格而不是冒号的struct标记中:type Example struct {
XMLName xml.Name `xml:"Example"`
Paragraphs []string `xml:"xhtml p"`
Divs []string `xml:"xhtml div"`
}
这将给出相同的输出。在Go Playground上尝试一下。查看相关问题:Parse Xml in GO for atttribute with ":" in tag
关于xml - 在元素标记Golang中解码包含 “:”的xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63953577/