I've got a WPF C# program and at one point I need to serialize objects to XML. In other places, I've been using this:
TextWriter writer = new StreamWriter(xmlFilePath);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MYOBJECT_TYPE));
try
{
xmlSerializer.Serialize(writer, MYOBJECT);
}
catch (Exception ex)
{
MessageBox.Show("Exception occured while writing to Xml" + ex.Message);
}
finally
{
writer.Close();
}
This is fantastic, but this means I have to have a different XML file for every object I want to serialize. How do I use this method (with the least amount of modifications) to serialize the object to the XML WITHIN a parent element? That way, when I want to deserialize the object later, I can just find the element that I want, and deserialize everything within that element.
As requested, here is CreateDefaultXml();
:
static void CreateDefaultXml()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<StoredObjects></StoredObjects>");
XmlNode root = doc.DocumentElement;
try
{
doc.Save(xmlFilePath);
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while creating Xml" + ex.InnerException);
}
}
EDIT:
Currently, this is what I've got (but it throws an exception There was an error generating the XML document.
)
if (!File.Exists(xmlFilePath))
CreateDefaultXml();
XDocument doc = XDocument.Load(xmlFilePath);
var element = doc.Descendants("Object").Where(x => x.Attribute("Name").Value.Equals("objectName")).SingleOrDefault();
if (element == null)
{
element = new XElement("Object", new XAttribute("Name", objectName));
doc.Element("StoredObjects").Add(element);
}
XmlWriter writer = element.CreateWriter();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MYOBJECT_TYPE));
try
{
xmlSerializer.Serialize(writer, MYOBJECT);
}
catch (Exception ex)
{
MessageBox.Show("Exception occured while writing to Xml: " + ex.Message);
}
finally
{
writer.Close();
doc.Save(xmlFilePath);
}