xml - 解析领先的XML注释

标签 xml go comments

我想处理一个配置文件。该文件应由应用程序读取和写入。配置文件应包含注释,以提供有关配置标签的信息。
标签内的注释没有问题。我使用'xml:",comment"'标记。
但是我无法在<ServerConfig>标记之外获得评论

<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment I cannot get -->
<ServerConfig>
  <!-- This is a comment I can get -->
  <KeyStore>/tmp/test</KeyStore>
</ServerConfig>
我可以使用解析ServerConfig标记内的注释
type ServerConfig struct {
   Comment string `xml:",comment"`
   KeyStore string
}
如何对主要评论进行Unmarshal()

最佳答案

您可以使用xml.NewDecoder逐行读取xml并实现自定义解析算法

const configXml =`<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a comment I cannot get -->
<ServerConfig>
  <!-- This is a comment I can get -->
  <KeyStore>/tmp/test</KeyStore>
</ServerConfig>`
dec := xml.NewDecoder(strings.NewReader(configXml))
for{
    tok, err := dec.Token()
    if err != nil && err != io.EOF {
        panic(err)
    } else if err == io.EOF {
        break
    }
    if tok == nil {
        fmt.Println("token is nil")
    }
    switch toke := tok.(type) {
    case xml.Comment:
        fmt.Println(string(toke))
    }
}
oji playground
 This is a comment I cannot get 
 This is a comment I can get 

关于xml - 解析领先的XML注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64315232/

相关文章:

session - Gorilla Sessions - 如何根据请求自动更新 Cookie 过期时间?

mongodb - MongoDB 中的嵌套注释

java - 是否可以在右侧而不是顶部创建文档注释?

comments - 是否可以在 Cobol 中添加内联注释

php - 使用 PHP 生成 XML 文件

android - 偏好 Activity 与偏好 fragment ?

带有连续图像按钮的 Android XML 布局

Go http 监听器,每秒更新一次数据

testing - 如果直接访问其字段,如何模拟结构

android - relativelayout、include 和layout_alignParentBottom 不起作用