0

I am using XmlSeriazlier to deserialize xml file.

var serializer = new XmlSerializer(typeof(T));
using (var reader = document.CreateReader())
   var result = (T)serializer.Deserialize(reader);

Xml can contain elements with different casing. Sample

<Layers>
    <Layer name="something" />
    <Layer name="anything" />
    <layer name="nothing" /> ====> 'l' instead of 'L'
</Layers>

Now my class is like this.

public class Layers
{
    [XmlElement("Layer")]
    public List<Layer> Layers { get; set; }
}

Now this will not read 'layer' from the xml. How I can read all xml elements and save them in one list.

fhnaseer
  • 7,159
  • 16
  • 60
  • 112
  • 3
    Xml is case sensitive, so why not just make sure that the Xml file is correct in the first place? – Sean Apr 17 '20 at 09:30
  • @Sean Old legacy xmls which cannot be changed. So have to support these. – fhnaseer Apr 17 '20 at 09:32
  • Related: [Case insensitive XML parser in c#](https://stackoverflow.com/q/9334771/3744182), [Deserialize/Read xml when casing of elements is inconsistent.](https://stackoverflow.com/q/45776598/3744182). – dbc Apr 17 '20 at 13:59
  • Another option would be to create an XmlReader [decorator](https://en.wikipedia.org/wiki/Decorator_pattern) as shown [here](http://referencesource.microsoft.com/#System.Xml/System/Xml/Core/XmlWrappingReader.cs) and [here](https://msdn.microsoft.com/en-us/library/t2abc1zd(v=vs.71).aspx) (under *Chaining XmlReaders*) then subclass the decorator and normalize the case all the element and attribute names. – dbc Apr 17 '20 at 14:01

1 Answers1

0

You could make your Layer class inherit IXmlSerializable and implement something like the below code in your ReadXml implementation:

while (!reader.EOF)
{
    // Use string.Compare with StringComparison.OrdinalIgnoreCase to ignore case
    if (reader.NodeType == XmlNodeType.Element && string.Compare(reader.Name, "Layer", StringComparison.OrdinalIgnoreCase))
    {
        // reading code
    }
    else
    {
        reader.Read();
    }
}

Note that I haven't test the code, but this might be an approach to your problem.