0

I have some XML that I need to work with, which follows a particular naming strategy:

<DOC_ROOT>
    <LIST_WRAPPER
        wrapperAttribute = "Something"
    >
        <LIST_ELEMENT
                elementAttribute = "Non-Default" >Element Text</LIST_ELEMENT>
        <LIST_ELEMENT
                elementAttribute = "Something Else" >Different Element Text</LIST_ELEMENT>
    </LIST_WRAPPER>
</DOC_ROOT>

And I have the corresponding classes to which I want to deserialize:

[XmlRoot]
public record DocRoot
{
    [XmlElement]
    public ListWrapper ListWrapper { get; set; }
}

[XmlRoot]
public record ListWrapper
{
    [XmlAttribute]
    public string WrapperAttribute { get; set; }
    [XmlElement]
    public List<ListElement> ListElement { get; set; }
}

[XmlRoot]
public record ListElement
{
    [XmlAttribute]
    public string ElementAttribute { get; set; }
    [XmlText]
    public string Text { get; set; }
}

For whatever reason, the default XmlSerializer does not understand the connection between items in different naming conventions, that wrapperAttribute should become WrapperAttribute. Of course, I can sidestep this problem by explicitly annotating the symbol that corresponds to a given property:

[XmlRoot("LIST_WRAPPER")]
public record ListWrapper
{
    [XmlAttribute("wrapperAttribute")]
    public string WrapperAttribute { get; set; }
    [XmlElement("LIST_ELEMENT")]
    public List<ListElement> ListElement { get; set; }
}

I'm wondering if there's some way that I could write a custom XmlSerializer, XmlTextReader, and XmlTextWriter that can automatically intuit the process of converting symbols from the XML which have a bunch of different cases into C# where everything is PascalCase, and back into the needed XML (following the chosen case strategy) when serializing.

Of course, I came across Deserialize/Read xml when casing of elements is inconsistent, but the chosen answer involves transforming the XML into JSON, and then deserializing from JSON instead, which is overhead that I'd prefer to avoid (if possible).

  • 1
    Yes. You could write your own XmlReader that wraps the XmlTextReader and fiddles with the names. But it would be complex if the XmlSerializer asked for nodes by normalized name, and you had to match the requested name to the names in the XML. A simpler approach would be to read a sample file as an XDocument and generate the annotated class definitions. – David Browne - Microsoft Jun 29 '23 at 20:30
  • Agreed, standard practice is to just generate the classes and correct naming attributes using a tool – Charlieface Jun 29 '23 at 22:41

0 Answers0