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