首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Go XML chardata打印空行

Go XML chardata打印空行
EN

Stack Overflow用户
提问于 2020-12-17 09:48:48
回答 1查看 151关注 0票数 2

我有一个基本的xml字段,它看起来像这个<cpe test="123">cpe:/a:openbsd:openssh:5.3p1</cpe>,我想使用Go解除它的编组。我创建了这个对象,当它通常解组和打印test属性时,括号中的内容总是被打印为空的。

代码语言:javascript
复制
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 test="123">cpe:/a:openbsd:openssh:5.3p1</cpe>`

    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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-17 10:08:02

chardata是一个选项,而不是XML标记或属性名,因此如果您只需指定一个选项,就必须在它前面加上一个逗号:

代码语言:javascript
复制
Value   string   `xml:",chardata"`

也要检查错误:

代码语言:javascript
复制
// 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)

这将输出(在围棋游乐场上尝试它):

代码语言:javascript
复制
err: <nil>
attribute: 123
chardata: cpe:/a:openbsd:openssh:5.3p1
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65338250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档