I need to deserialize an XML file with known elements in unknown order and count:
<?xml version="1.0" encoding="utf-8"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ConfigType1 Label="abc">
:
</ConfigType1>
<ConfigType1 Label="def">
:
</ConfigType1>
<ConfigType3 Label="ghi"/>
:
</ConfigType3>
<ConfigType1 Label="jkl">
:
</ConfigType1>
<ConfigType2 Label="mno">
:
</ConfigType2>
<ConfigType3 Label="pqr">
:
</ConfigType3>
:
</Config>
My approach is that for each element type there is a class that can serialize and deserialize itself. MyXmlSerializerFactory calls Deserialize() of the corresponding element class depending on the element type.
Am I on the right way with the following approach? I get an XML element in the OnUnknownElement event. How can this be deserialized in the element class? There is only xmlSerializer.Deserialize() with parameters of type Stream, TextReader and XmlReader, but not XmlElement?
namespace MyNamespace
{
[XmlRoot("Config")]
public class Config
{
private static List<MyConfigElement> _configElements = new();
private Config()
{
}
public static Config Deserialize(string path)
{
Config config;
XmlDeserializationEvents deserializationEvents = new XmlDeserializationEvents();
deserializationEvents.OnUnknownElement += (sender, args) =>
{
XmlElement xmlElement = args.Element;
// => How can I convert XmlElement to Stream, TextReader or XmlReader?
_configElements.Add(MyXmlSerializerFactory.Deserialize(???));
};
var xmlSerializer = new XmlSerializer(typeof(Config));
using (var stream = new FileStream(path, FileMode.Open))
using (var xmlReader = XmlReader.Create(stream))
{
config = (Config)xmlSerializer.Deserialize(xmlReader, deserializationEvents);
config.Path = path;
}
return config;
}
Thank you very much for hints!