mikefarah/yq · error
invalid XML: Encountered chardata [%v] outside of XML node
Error message
invalid XML: Encountered chardata [%v] outside of XML node
What it means
While streaming XML tokens, the decoder received character data (text) before any element had started — i.e. there is non-whitespace text at the top of the document outside the root node. Valid XML permits only whitespace and comments before the root element, so after trimming non-graphable characters any remaining leading chardata makes the document invalid.
Source
Thrown at pkg/yqlib/decoder_xml.go:299
n: &xmlNode{},
label: label,
}
// Extract attributes as children
for _, a := range se.Attr {
if dec.prefs.KeepNamespace {
if a.Name.Space != "" {
a.Name.Local = a.Name.Space + ":" + a.Name.Local
}
}
elem.n.AddChild(dec.prefs.AttributePrefix+a.Name.Local, &xmlNode{Data: []string{a.Value}})
}
case xml.CharData:
// Extract XML data (if any)
newBit := trimNonGraphic(string(se))
if !started && len(newBit) > 0 {
return fmt.Errorf("invalid XML: Encountered chardata [%v] outside of XML node", newBit)
}
if len(newBit) > 0 {
elem.n.Data = append(elem.n.Data, newBit)
elem.state = "chardata"
log.Debugf("chardata [%v] for %v", elem.n.Data, elem.label)
}
case xml.EndElement:
if elem == nil {
log.Debug("no element, probably bad xml")
continue
}
log.Debugf("end element %v", elem.label)
elem.state = "finished"
// And add it to its parent list
if elem.parent != nil {
elem.parent.n.AddChild(elem.label, elem.n)
}View on GitHub (pinned to 8b5af0694b)
Solutions
- Remove stray text before the XML root element (the offending text is shown in the message)
- Wrap loose text in a root element if it is meant to be data
- Check for a truncated file that begins mid-text
- Ensure the input is XML and not HTML/plain text
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at pkg/yqlib/decoder_xml.go:299 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of mikefarah/yq@8b5af0694b (2026-09-05).
Data as JSON: /api/errors/a4bc2e28bf018b5f.
Report an issue: GitHub.