序列化对象到XML [英] Serialize an object to XML
本文介绍了序列化对象到XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我继承了一个C#类。我已经成功地建造的对象。但我需要的对象序列化到XML。有没有一种简单的方法来做到这一点?
I have a C# class that I have inherited. I have successfully "built" the object. But I need to serialize the object to XML. Is there an easy way to do it?
它看起来像类已设置了序列化,但我不知道如何让XML重新presentation。我的类定义是这样的:
It looks like the class has been set up for serialization, but I'm not sure how to get the XML representation. My class definition looks like this:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
...
}
下面是我想我能做到的,但它不工作:
Here is what I thought I could do, but it doesn't work:
MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
我如何得到这个对象的XML重新presentation?
How do I get the XML representation of this object?
推荐答案
您必须使用XmlSerializer的用于XML序列化。下面是一个示例代码段。
You have to use XmlSerializer for XML serialization. Below is a sample snippet.
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
var subReq = new MyObject();
using(StringWriter sww = new StringWriter())
using(XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, subReq);
var xml = sww.ToString(); // Your XML
}
这篇关于序列化对象到XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文