xml - 在元素标记Golang中解码包含 “:”的xml

标签 xml go struct unmarshalling

我已经开始解析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时,我得到了ParagraphsDivs的空 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/

相关文章:

c# - 如何使用 c#.net 读取 XML 中的 XML 节点

session - Golang 和 Gorilla session - 缓存阻止注销功能

struct - 我可以限制结构的生命周期污染吗?

c - 将结构体的所有成员(相同的基本数据类型)初始化为一个给定值

c - 尝试访问和写入结构成员后程序崩溃

c++ - 如何在 C++ 中从 Internet 下载 xml

c# - 在 C# 中填充不包含 XML 文档值的 TreeView

java - 检索 Jaxb 转换的 Enum 类中的 @XmlEnumValue 注释属性值

mongodb - UUID 作为 _id 错误 - 不能将数组用于 _id

caching - Go 是否缓存 DNS 查找?