XmlSerializer.Serialize, XmlWriter.Create and XmlDocument working together?

A

Andy B

I have the following empty object:

XmlDocument ContractXmlDocument = new XmlDocument();

I was reading that you could use XmlSerializer.Serialize to serialize an
object (Contract) in this case to an XmlDocument object (above). How exactly
do you do this? I have the code for putting the object into a physical xml
file, but not into another Xml formatted Document object. My serialize to a
file code looks like this:

XmlWriter FileWriter = new XmlWriter();
Stream FileStream = new Stream(@"Contract.xml");
XmlSerializer.Serialize(Contract, FileStream);

Any ideas?
 
M

Marc Gravell

As long as the object-tree isn't obscenely big, just serialize to a
string; you could also use MemoryStream, but that will just force an
encoding into both the write and read for no real benefit:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[Serializable]
public class Foo
{
[XmlAttribute]
public string Bar { get; set; }
}
class Program
{
static void Main(string[] args)
{
// instantiate
Foo foo = new Foo { Bar = "abc" };

// serialize
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, foo);
string xml = writer.ToString();

// parse
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top