dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.24k stars 4.73k forks source link

XMLSerializer UnknownAttribute event does not fire on built-in types #96683

Open alankbi opened 9 months ago

alankbi commented 9 months ago

Description

When parsing the following XML:

<Document>
    <Test unknown="attribute">
        ...
    </Test>
</Document>

Into the following classes:

public class Test
{
    ...
}

public class Document
{
    public Test Test;
}

XMLSerializer's Deserialize function correctly fires an UnknownAttribute event. However, for the following XML:

<Document>
    <TestList unknown="attribute not triggered">
        ...
    </TestList>
    <StringField unknown="attribute not triggered">random</StringField>
</Document>

And classes:

public class Document
{
    [XmlArrayItem("Test")]
    public List<string> TestList;
    public string StringField;
}

No event is fired for the unknown attribute on either the list or the string field.

Reproduction Steps

Using the XML and classes above, run the following code to verify that HandleUnknownAttribute is not called when erroneous attributes are present on string or list fields (or any built-in type it seems, including ints, bools, etc.):

var serializer = new XmlSerializer(typeof(Document));
serializer.UnknownAttribute += HandleUnknownAttribute

using (var reader = new FileStream("filename.xml", FileMode.Open))
{
    serializer.Deserialize(reader);
}

...

public void HandleUnknownAttribute(object sender, XmlAttributeEventArgs e)
{
    // not triggered for TestList or StringField
}

Expected behavior

An UnknownAttribute event should be fired and the event handler called

Actual behavior

No event is fired

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

alankbi commented 9 months ago

Regardless of whether this is a bug or known limitation with XMLSerializer, is there a workaround to force validation for all unknown attributes? These attributes get dropped during deserialization, so I also can't perform a post-deserialization check on the resulting objects.

acaly commented 9 months ago

Have you considered implementing IXmlSerializable?