2

What is the best way to convert the C# object to XmlEmenet? Do I just use XmlSerializer and import the XmlNode or is there a better way?

This is what I found out there wondering if there is any other better way.

public XmlElement Serialize(XmlDocument document)
{
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    XmlElement returnVal;
    XmlSerializer serializer = new XmlSerializer(this.GetType());
    MemoryStream ms = new MemoryStream();
    XmlTextWriter tw = new XmlTextWriter(ms, UTF8Encoding.UTF8);
    XmlDocument doc = new XmlDocument();
    tw.Formatting = Formatting.Indented;
    tw.IndentChar = ' ';
    serializer.Serialize(tw, this, ns);
    ms.Seek(0, SeekOrigin.Begin);
    doc.Load(ms);
    returnVal = document.ImportNode(doc.DocumentElement, true) as XmlElement;
    return returnVal;
}
svick
  • 236,525
  • 50
  • 385
  • 514
Natasha Thapa
  • 979
  • 4
  • 20
  • 41

1 Answers1

0

You can make that into an Extension Method on the Object Type so you don't have to put that method in a bunch of different classes.

NoAlias
  • 9,218
  • 2
  • 27
  • 46