Skip to content

Commit f34cdc3

Browse files
authoredMar 22, 2025··
parser/metadecoder: Improve errors for non-map XML root values
Previously, the XML decoder would panic when encountering a root element with a non-map value due to an unsafe type assertion. The fix adds proper type checking before the map conversion and provides clear error messages to help users identify and fix invalid XML structures. Example error for invalid XML like: <root>just text</root> Will now return: "XML root element 'root' must be a map/object, got string"
1 parent 52561d5 commit f34cdc3

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed
 

‎parser/metadecoders/decoder.go

+13-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,19 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error {
152152
if err != nil {
153153
return toFileError(f, data, fmt.Errorf("failed to unmarshal XML: %w", err))
154154
}
155-
xmlValue = xmlRoot[xmlRootName].(map[string]any)
155+
156+
// Get the root value and verify it's a map
157+
rootValue := xmlRoot[xmlRootName]
158+
if rootValue == nil {
159+
return toFileError(f, data, fmt.Errorf("XML root element '%s' has no value", xmlRootName))
160+
}
161+
162+
// Type check before conversion
163+
mapValue, ok := rootValue.(map[string]any)
164+
if !ok {
165+
return toFileError(f, data, fmt.Errorf("XML root element '%s' must be a map/object, got %T", xmlRootName, rootValue))
166+
}
167+
xmlValue = mapValue
156168
}
157169

158170
switch v := v.(type) {

‎parser/metadecoders/decoder_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ func TestUnmarshalToMap(t *testing.T) {
9999
// errors
100100
{`a = b`, TOML, false},
101101
{`a,b,c`, CSV, false}, // Use Unmarshal for CSV
102+
{`<root>just a string</root>`, XML, false},
102103
} {
103104
msg := qt.Commentf("%d: %s", i, test.format)
104105
m, err := d.UnmarshalToMap([]byte(test.data), test.format)

0 commit comments

Comments
 (0)
Please sign in to comment.