将对象列表序列化为XDocument

时间:2011-05-25 07:42:32

标签: c# xml serialization linq-to-xml

我正在尝试使用以下代码将对象列表序列化为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构造函数没有对象列表?怎么解决这个问题?

3 个答案:

答案 0 :(得分:2)

我认为最后一行应该是

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

答案 1 :(得分:0)

XDocument的ctor期望其他对象,如XElement和XAttribute。看看文档。您正在寻找的是XDocument.Parse(...)。

以下内容也应该有效(未经测试):

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

现在,您可以直接在不使用StringBuilder的情况下编写文档。应该快得多。

答案 2 :(得分:0)

我以这种方式完成了工作。

private void button2_Click(object sender, EventArgs e)
{
    List<BrokerInfo> listOfBroker = new List<BrokerInfo>()
    {
    new BrokerInfo { Section = "TestSec1", Lineitem ="TestLi1" },
    new BrokerInfo { Section = "TestSec2", Lineitem = "TestLi2" },
    new BrokerInfo { Section = "TestSec3", Lineitem ="TestLi3" }
    };

    var xDoc = new XDocument(new XElement("Engagements",
        new XElement("BrokerData",
     from broker in listOfBroker

     select new XElement("BrokerInfo",
       new XElement("Section", broker.Section),
       new XElement("When", broker.Lineitem))
    )));

    xDoc.Save("D:\\BrokerInfo.xml");
}

public class BrokerInfo
{
    public string Section { get; set; }
    public string Lineitem { get; set; }
}