本文介绍了将对象列表序列化到XDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码将对象列表序列化为XDocument,但是我收到一条错误消息,指出不能将非空格字符添加到内容中""
I'm trying to use the following code to serialize a list of objects into XDocument, but I'm getting an error stating that "Non white space characters cannot be added to content"
public XDocument GetEngagement(MyApplication application)
{
ProxyClient client = new ProxyClient();
List<Engagement> engs;
List<Engagement> allEngs = new List<Engagement>();
foreach (Applicant app in application.Applicants)
{
engs = new List<Engagement>();
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
构造函数不包含对象列表吗?该如何解决?
What am I doing wrong? Is it the XDocument
constructor that doesn't take a list of objects? how do solve this?
推荐答案
我认为最后一行应该是
return XDocument.Parse(sb.ToString());
完全切掉序列化器可能是一个主意,从List<>
直接创建XDoc应该很容易.这样就可以完全控制结果.
And it might be an idea to cut out the serializer altogether, it should be easy to directly create an XDoc from the List<>
. That gives you full control over the outcome.
大致:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!