Unmarshall xml在元素标记Golang中包含“:”

问题描述

我已经开始解析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都得到了空白。 有什么想法我做错了吗?

解决方法

从struct标记中删除标记名称空间,它将起作用:

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
        ]}

如果确实要指定名称空间,则必须将其添加到带有空格而不是冒号的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