c# loop through xml child nodes and deserialize

287 Views Asked by At

I'm trying to loop into an XmlDocument to serialize objects. Let's suppose an simple xml :

<?xml version="1.0" encoding="iso-8859-15"?>
<root>
    <message>
        <id>1</id>
        <text>test</text>
    </message>
    <message>
        <id>2</id>
        <text>test 2</text>
    </message>
</root>

So this is my c# program :

class Program
{
    static void Main(string[] args)
    {
        XmlReaderSettings readerSettings = new XmlReaderSettings();
        readerSettings.IgnoreComments = true;

        XmlSerializer serializer = new XmlSerializer(typeof(Message));

        XmlReader xmlReader = XmlReader.Create(@"..\..\test.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(xmlReader);



        foreach(XmlElement element in doc.DocumentElement.ChildNodes)
        {
            Console.WriteLine($"id : {element.SelectSingleNode("id").InnerText}, message : {element.SelectSingleNode("text").InnerText}");
            Message message = (Message)serializer.Deserialize(XmlReader.Create(element.OuterXml.ToString()));
        }

        Console.ReadLine();
    }
}

public class Message
{
    public int id;
    public string text; 
}

but i got an error Illegal characters in path, but the print is okay, what's wrong ? and is there a way to serialize directly the XmlElement without go through the tostring() ?

1

There are 1 best solutions below

0
Lucas Weibel On

Ok, i found the problem. The serializer is looking for a tag named Message like the name of the class but the tag was message with an lowercase m. It is still possible to differentiate the name of the class and the label of the tag and associate them with a decorator as :

[XmlRoot(ElementName = "message")]
public class Message
{
    public int id { get; set; }
    public string? text { get; set; }
}