Alex Rivera | Logout

How do I create an XmlNode from a call to XmlSerializer.Serialize?

Asked 2008-09-05T16:50:35.973
16

I am using a class library which represents some of its configuration in .xml. The configuration is read in using the XmlSerializer. Fortunately, the classes which represent the .xml use the XmlAnyElement attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.

<?xml version="1.0" encoding="utf-8"?>
<Config>
  <data>This is some data</data>
  <MyConfig>
    <data>This is my data</data>
  </MyConfig>
</Config>

This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own XmlSerializer instances with a XmlNodeReader against the internal XmlNode.

public class Config
{
    [XmlElement]
    public string data;

    [XmlAnyElement]
    public XmlNode element;
}

public class MyConfig
{
    [XmlElement] 
    public string data;
}

class Program
{
    static void Main(string[] args)
    {
        using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open))
        {
            XmlSerializer xser1 = new XmlSerializer(typeof(Config));
            Config config = (Config)xser1.Deserialize(fs);

            if (config.element != null)
            {
                XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
                MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element));
            }
        }
    }

I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml?

I realize that I have to initially call XmlSerializer.Serialize on my d

Edit
Report

1 Answer

3

It took a bit of work, but the XPathNavigator route does work... just remember to call .Close on the XmlWriter, .Flush() doesn't do anything:

//DataContractSerializer serializer = new DataContractSerializer(typeof(foo));
XmlSerializer serializer = new XmlSerializer(typeof(foo));

XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
XmlWriter writer = nav.AppendChild();
writer.WriteStartDocument();
//serializer.WriteObject(writer, new foo { bar = 42 });
serializer.Serialize(writer, new foo { bar = 42 });
writer.WriteEndDocument();
writer.Flush();
writer.Close();

Console.WriteLine(doc.OuterXml);
answered 2008-11-21T03:11:44.923

Your Answer