我有从xsd生成的类,我想用它来创建一个通过网络发送的xml。我只想在内存中创建文档,将其转换为字符串/ byte []并发送它。我的印象是,一旦填充了类,我就可以执行一个tostring(),它会返回整个文档。情况似乎并非如此......我在这里做错了什么?
@event myEvent = new @event();
myEvent.name = "AddProgram";
myEvent.version = 8.0M;
DateTime myDateTime = new DateTime();
myDateTime = DateTime.Now;
myEvent.time = myDateTime;
detail myDetail = new detail();
myDetail.name = "Program1"
myEvent.detail = myDetail;
Controller controller = new Controller();
controller.actionSpecified = true;
controller.action = ControllerAction.Create;
myDetail.Controller = controller;
String xmlString = myEvent.ToString(); //this is where i would expect a string.
我所能摆脱的是:“事件”
答案 0 :(得分:1)
我不知道你在哪里得到你的信息,ToString()会给你一个类的xml表示,但事实并非如此。你应该做的是参考这篇关于XML序列化的文章。
http://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx
如果您有一类Type事件,那么您需要执行以下操作将其序列化为XML。另外,作为一个小小的问题,如果可能的话,我将远离使用关键字作为类或变量定义,但如果你无法控制自己的双手。
@event myEvent = new @event();
myEvent.name = "AddProgram";
myEvent.version = 8.0M;
string xmlIWant= "";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(@event);
using (StringWriter writer = new StringWriter())
{
x.Serialize(writer, myEvent);
xmlIWant = writer.ToString();
}