将对象列表序列化为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。 应该快得多。