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).