4

I've been trying to find an easy way to write XML using the XmlReader/XmlWriter. I don't really like using the interface "IXmlSerializable", but I've got no choice for some of my dataclass.

Anyway, what I want to do is quite simple:

private MyClass myObject;
public void WriteXml(XmlWriter writer)
{
    writer.WriteObject(myObject); // <-- this method doesn't exists
}

So, I found 2 work around:

  1. Write my own routine to write my object manually. Quite ridiculous since .Net already does it.
  2. Create a new serializer using a StringWriter and use the WriteValue(string) method.

I haven't tested the second yet but I think it will probably work (not sure because of the ReadValue result).

Then my question is: Am I missing something important or is it the only way? Or is there a better way to handle that?

Thanks.

Sauleil
  • 2,573
  • 1
  • 24
  • 27
  • Have you had a look at LINQ to XML? That is a bit or work but works a treat. – Pieter Dec 11 '10 at 01:38
  • Yeah, I know the idea, but never used it. But here my problem is that my complex object has many sub objects and each one defines XmlAttributes. So I need to read those attributes. I just don't want to write blindly elements. – Sauleil Dec 11 '10 at 01:41

2 Answers2

6

After playing around, I found something quite simple. Here is the code I was playing with for those who are wondering how I fixed my problem (similar for reading and element):

    public static void WriteElement(XmlWriter writer, string name, object value)
    {
        var serializer = new XmlSerializer(value.GetType(), new XmlRootAttribute(name));
        serializer.Serialize(writer, value);
    }

I don't know why I was complicating the problem, but it cannot be more simpler than that.

Sauleil
  • 2,573
  • 1
  • 24
  • 27
0

Try using the XmlDocument class. It uses the XmlNode as the basis for easily writing out xml. You can also serialize a class, or use the DataSet class to write out xml, or read it back into a dataset or XmlDocument type structure.

Cyber Slueth Omega
  • 399
  • 1
  • 3
  • 19