将对象序列化为 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 表示.我的类定义如下所示:
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 表示?
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();
var xml = "";
using(var sww = new StringWriter())
{
using(XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, subReq);
xml = sww.ToString(); // Your XML
}
}
这篇关于将对象序列化为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文