Parse leading XML comment

Viewed 114

I'd like to handle a configuration file. This file should be read and write by the application. The configuration file should contain comments to provide information about the configuration tags.

The comments inside the tags is no problem. I use the 'xml:",comment"' tags. But I cannot get the comments outside the <ServerConfig> tag

<?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>

I am able to parse the comment inside the ServerConfig tag using

type ServerConfig struct {
   Comment string `xml:",comment"`
   KeyStore string
}

How can I Unmarshal() the leading comment?

1 Answers

You can use xml.NewDecoder to read the xml line-by-line and implement custom parsing algorithm

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

playground

 This is a comment I cannot get 
 This is a comment I can get 
Related