You can use xml serialization in your classes:
[XmlType("Root", Namespace = "http://example.com/Root")]
[XmlRoot(Namespace = "http://example.com/Root.xsd", ElementName = "Root", IsNullable = false)]
public class Root {
[XmlElement("Something")]
public Something Something { get; set; }
}
public class Something {
[XmlElement("SomethingElse")]
public SomethingElse SomethingElse { get; set; }
}
public class SomethingElse {
[XmlText]
public string Text { get; set; }
}
Serialize it as follows:
var serializer = new XmlSerializer(typeof(Root));
serializer.Serialize(outputStrem, myRoot);
Then you can check before deserializing, for example:
var serializer = new XmlSerializer(typeof(Root));
string xml = @"
<Root xmlns='http://example.com/Root'>
<Something>
<SomethingElse>Yep!</SomethingElse>
</Something>
</Root>";
Debug.Assert(serializer.CanDeserialize(new XmlTextReader(new StringReader(xml))));
And then just deserialize:
Root newRoot = (Root)serializer.Deserialize(inputStream);
Your XSD is implicit. This matches your classes. To use richer XSDs, you can take a chance at Schema Providers .
source
share