将对象列表序列化为XDocument
我正在尝试使用以下代码将对象列表序列化为XDocument,但我收到一条错误消息,指出“无法将非空格字符添加到内容中”
public XDocument GetEngagement(MyApplication application) { ProxyClient client = new ProxyClient(); List engs; List allEngs = new List(); foreach (Applicant app in application.Applicants) { engs = new List(); engs = client.GetEngagements("myConnString", app.SSN.ToString()); allEngs.AddRange(engs); } DataContractSerializer ser = new DataContractSerializer(allEngs.GetType()); StringBuilder sb = new StringBuilder(); System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings(); xws.OmitXmlDeclaration = true; xws.Indent = true; using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(sb, xws)) { ser.WriteObject(xw, allEngs); } return new XDocument(sb.ToString()); }
我究竟做错了什么? 是不是XDocument
构造函数不采用对象列表? 怎么解决这个?
我认为最后一行应该是
return XDocument.Parse(sb.ToString());
完全删除序列化程序可能是一个想法,从List<>
直接创建XDoc应该很容易。 这使您可以完全控制结果。
大致:
var xDoc = new XDocument( new XElement("Engagements", from eng in allEngs select new XElement ("Engagement", new XAttribute("Name", eng.Name), new XElement("When", eng.When) ) ));
XDocument的ctor期望其他对象,如XElement和XAttribute。 看看文档。 您正在寻找的是XDocument.Parse(…)。
以下应该也可以工作(未经测试):
XDocument doc = new XDocument(); XmlWriter writer = doc.CreateNavigator().AppendChild();
现在,您可以直接写入文档而无需使用StringBuilder。 应该快得多。
上述就是C#学习教程:将对象列表序列化为XDocument分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/962457.html