如何使用go检查XML文件中是否存在标签?

I don't know the tags that are present in the XML file. I'd like to know whether a certain tag exists. For example, suppose the file is like this:

<?xml version='1.1' encoding='UTF-8'?>
<tag1>
    <tag2></tag2>
</tag1>
<tag3/>

Here I'd like to check whether tag2 exists. The only way to parse XML files using go is by defining structs, but for that, I'll have to know what tags are present in the file, which I don't.

You may use event-driven XML parsing. Create an xml.Decoder using xml.NewDecoder(), and parse the content of the XML by calling Decoder.Token() repeatedly (in a loop).

You can check if a token is a start element using a type assertion, checking for the xml.StartElement type. If the assertion succeeds, you can check the name of the element if it matches the one you're looking for.

This is how it could look like:

func checkTag(src, tag string) (bool, error) {
    decoder := xml.NewDecoder(strings.NewReader(src))

    for {
        t, err := decoder.Token()
        if err != nil {
            if err == io.EOF {
                return false, nil
            }
            return false, err
        }
        if se, ok := t.(xml.StartElement); ok {
            if se.Name.Local == tag {
                return true, nil
            }
        }
    }
}

Testing it:

func main() {
    fmt.Println(checkTag(src, "tag2"))
    fmt.Println(checkTag(src, "tagX"))
}

const src = `<?xml version='1.0' encoding='UTF-8'?>
<tag1>
    <tag2></tag2>
</tag1>
<tag3/>`

Output (try it on the Go Playground):

true <nil>
false <nil>

As you can see, tag2 was properly found in the source XML, and tagX was properly not found.

See related question: Unmarshalling heterogeneous list of XML elements in Go

One way would be to use XPath and the xmlpath package:

xml := `<?xml version='1.0' encoding='UTF-8'?><tag1><tag2>foo</tag2></tag1><tag3/>`

path := "/tag1/tag2"
compiledPath := xmlpath.MustCompile("/tag1/tag2")
root, err := xmlpath.Parse(strings.NewReader(xml))
if err != nil {
    log.Fatal(err)
}
if value, ok := compiledPath.String(root); ok {
    fmt.Printf("Found tag at path %v. Value: %v
", path, value)

} else {
    fmt.Printf("Tag at path %v not found
", path)
}