简体   繁体   中英

C# Object to XmlElement

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;
}

您可以将其放入“对象类型”的“扩展方法”中,从而不必将该方法放入一堆不同的类中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM