将对象列表序列化到 XDocument
我尝试使用以下代码将对象列表序列化到 XDocument 中,但收到错误消息“无法将非空白字符添加到内容中” “
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
构造函数不接受对象列表吗?如何解决这个问题?
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());
}
What am I doing wrong? Is it the XDocument
constructor that doesn't take a list of objects? how do solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
XDocument 的构造函数需要其他对象,例如 XElement 和 XAttribute。查看文档。您正在寻找的是 XDocument.Parse(...)。
以下内容也应该有效(未经测试):
现在您可以直接写入文档,而无需使用 StringBuilder。应该会快很多。
The ctor of XDocument expects other objects like XElement and XAttribute. Have a look at the documentation. What you are looking for is XDocument.Parse(...).
The following should work too (not tested):
Now you can write directly into the document without using a StringBuilder. Should be much faster.
我就是这样完成工作的。
I have done the job this way.
我认为最后一行应该是
完全删除序列化器可能是一个想法,从
List<>
直接创建 XDoc 应该很容易。这使您可以完全控制结果。大致:
I would think that last line should be
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.Roughly: