Using xsd.exe you can generate a Class from your form schema (xsd) and then deserialize a form to an instance of that class. This makes it a lot easier to interact with its data.
The code for serialization and deserialization might look like this:
public static T Deserialize(Stream s)
{
T result = default(T);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlTextReader reader = new XmlTextReader(s))
{
result = (T)serializer.Deserialize(reader);
}
s.Close();
return result;
}
public static T Deserialize(string s)
{
return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(s)));
}
public static string Serialize(T o)
{
string result = null;
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = Encoding.UTF8;
using (MemoryStream stream = new MemoryStream())
{
using (XmlWriter writer = XmlTextWriter.Create(stream, settings))
{
serializer.Serialize(writer, o);
}
stream.Flush();
result = Encoding.UTF8.GetString(stream.ToArray());
}
return result;
}
However you lose the original processing instructions at the top of the XML file. If you want to keep those either do custom serialization using an XmlWriter or do some kind of merge code with the original XML and the XML coming from serialization.
Quite obvious if you think about it but I keep forgetting it :)