[英]C# Object to XmlElement
What is the best way to convert the C# object to XmlEmenet
? 将C#对象转换为XmlEmenet
的最佳方法是什么? Do I just use XmlSerializer
and import the XmlNode
or is there a better way? 我只是使用XmlSerializer
并导入XmlNode
还是有更好的方法?
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;
}
您可以将其放入“对象类型”的“扩展方法”中,从而不必将该方法放入一堆不同的类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.