我想处理一个配置文件。该文件应由应用程序读取和写入。配置文件应包含注释,以提供有关配置标签的信息。
标签内的注释没有问题。我使用'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/

10-14 16:27
查看更多