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() ?