Serializing a list of objects to XDocument

会有一股神秘感。 提交于 2019-12-31 05:01:29

问题


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?


回答1:


I would think that last line should be

 return XDocument.Parse(sb.ToString());

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:

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) )
    ));



回答2:


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):

XDocument doc = new XDocument();
XmlWriter writer = doc.CreateNavigator().AppendChild();

Now you can write directly into the document without using a StringBuilder. Should be much faster.



来源:https://stackoverflow.com/questions/6121097/serializing-a-list-of-objects-to-xdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!