将对象列表序列化到XDocument

问题描述 投票:1回答:3

我正在尝试使用以下代码将对象列表序列化为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构造函数不包含对象列表吗?该如何解决?

c# xml serialization linq-to-xml
3个回答
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) ) ));


0
投票
XDocument的核心要求其他对象,例如XElement和XAttribute。看一下文档。您正在寻找的是XDocument.Parse(...)。

以下内容也应该起作用(未经测试):

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

现在您无需使用StringBuilder即可直接写入文档。应该快得多。

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

© www.soinside.com 2019 - 2024. All rights reserved.