How to distinguish XML file types before deserialization?

I load MusicXML files into my program. Problem: There are two “dialects”, temporary and separated, that have different root nodes (and a different structure):

<?xml version="1.0" encoding='UTF-8' standalone='no' ?> <!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 2.0 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd"> <score-partwise version="2.0"> <work>...</work> ... </score-partwise> 

and

 <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE score-timewise PUBLIC "-//Recordare//DTD MusicXML 2.0 Timewise//EN" "http://www.musicxml.org/dtds/timewise.dtd"> <score-timewise version="2.0"> <work>...</work> ... </score-timewise> 

My code for deserializing a partial score so far is:

 using (var fileStream = new FileStream(openFileDialog.FileName, FileMode.Open)) { var xmlSerializer = new XmlSerializer(typeof(ScorePartwise)); var result = (ScorePartwise)xmlSerializer.Deserialize(fileStream); } 

What would be the best way to distinguish between two dialects?

+6
source share
2 answers

You can do this here using XDocument to XDocument file, read the root element to determine the type, and read it into your serializer.

 var xdoc = XDocument.Load(filePath); Type type; if (xdoc.Root.Name.LocalName == "score-partwise") type = typeof(ScorePartwise); else if (xdoc.Root.Name.LocalName == "score-timewise") type = typeof(ScoreTimewise); else throw new Exception(); var xmlSerializer = new XmlSerializer(type); var result = xmlSerializer.Deserialize(xdoc.CreateReader()); 
+5
source

I would create as serializers

 var partwiseSerializer = new XmlSerializer(typeof(ScorePartwise)); var timewiseSerializer = new XmlSerializer(typeof(ScoreTimewise)); 

Assuming there are only these two, I would call the CanDeserialize method on one

 using (var fileStream = new FileStream(openFileDialog.FileName, FileMode.Open)) { using (var xmlReader = XmlReader.Create(filStream)) { if (partwiseSerializer.CanDeserialize(xmlReader)) { var result = partwiseSerializer.Deserialize(xmlReader); } else { var result = timewiseSerializer.Deserialize(xmlReader); } } } 

Obviously, this is just an idea of ​​how to do this. If there were more options or according to your application design, I would use a more sophisticated way to call CanDeserialize , but this method is key in my opinion:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize.aspx

The XmlReader class can be found here:

http://msdn.microsoft.com/en-us/library/System.Xml.XmlReader(v = vs .110) .aspx

+2
source

All Articles