登录
首页 >  Golang >  Go问答

打印包含XML chardata的空行

来源:stackoverflow

时间:2024-02-24 10:51:26 304浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《打印包含XML chardata的空行》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个基本的 xml 字段,看起来像这样 cpe:/a:openbsd:openssh:5.3p1 我想使用 go 对其进行解组。我创建了该对象,虽然它通常会解组并打印测试属性,但括号内的内容始终打印为空。

package main

import (
    "fmt"
    "encoding/xml"
)

type Cpe struct {
    XMLName xml.Name `xml:"cpe"`
    Value   string   `xml:"chardata"`
    Res string   `xml:"test,attr"`
}

func main() {

    var inputXML = `cpe:/a:openbsd:openssh:5.3p1`

    byteValue := []byte(inputXML)
    
    // Create the onject
    var cpe Cpe
    
    // Unmarshal the xml using the Address object
    xml.Unmarshal(byteValue, &cpe)
    
    // prints the Res and Address Value
    fmt.Println(cpe.Res)
    fmt.Println(cpe.Value)  
}

这些东西的输出是 123nothing。通过谷歌搜索,我发现我可以使用 innerxml 而不是 chardata,它具有相同的结果。

演示:https://play.golang.org/p/7eyoxjnols4


解决方案


chardata 是一个选项,而不是 xml 标记或属性名称,因此如果您只指定选项,则必须在其前面添加逗号:

value   string   `xml:",chardata"`

还要检查错误:

// unmarshal the xml using the address object
err := xml.unmarshal(bytevalue, &cpe)
fmt.println("err:", err)

// prints the res and address value
fmt.println("attribute:", cpe.res)
fmt.println("chardata:", cpe.value)

这将输出(在 Go Playground 上尝试):

err: 
attribute: 123
chardata: cpe:/a:openbsd:openssh:5.3p1

到这里,我们也就讲完了《打印包含XML chardata的空行》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>