Build XML using linq to objects
I am trying to generate an XML file using the data from a class, which has a name and multiple addresses associated to the name. I am getting lost @ adding multiple addresses to the XElement. Can somebody please help me. Thanks in advance BB.
My Classes :
public class Subject
{
public ClueName name { get; set; }
public List driverAddress { get; set;}
}
public class DriverAddress
{
public string house { get; set; }
public string street1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip4 { get; set; }
}
private string BuildRequestXML(List <Subject> input)
{
string subjectId = "S1" ;
XElement req = new XElement("order",
new XElement("order_dataset",
new XElement("subjects",
from i in input
select
new XElement("subject", new XAttribute("id", subjectId),
开发者_如何学JAVA new XElement("name",
new XElement("first",i.name.first),
new XElement("middle", i.name.middle ),
new XElement("last", i.name.last)
)
)
),
new XElement("addresses",
input.Select(c => {c.driverAddress.Select (d =>
new XElement("address",
new XElement("street1",d.street1),
new XElement("city",d.city),
new XElement("state",d.state),
new XElement("postalcode",d.postalcode)
)).ToList ();
}).ToList()
)
)
);
}
I think the problem is in the input.Select(c => {c.driverAddress.Select (d =>
section.
You are already iterating though input as i, so can do along the lines of
from d in i.driverAddress
select new XElement("address",
new XElement("street1", d.Street1),
new XElement("street2", d.Street2),
etc...
UPDATE: Since driver addresses should not be output as children of the subject, try the following:
var addresses = new List<DriverAddress>();
input.ForEach(delegate(Subject s) { s.driverAddress.ForEach(d => addresses.Add(d)); });
string subjectId = "S1";
XElement req = new XElement("order",
new XElement("order_dataset",
new XElement("subjects",
from i in input
select
new XElement("subject", new XAttribute("id", subjectId),
new XElement("name",
new XElement("first", i.name.first),
new XElement("middle", i.name.middle),
new XElement("last", i.name.last)
)
)
),
new XElement("addresses",
from d in addresses
select new XElement("address",
new XElement("street1", d.street1),
new XElement("city", d.city),
new XElement("state", d.state),
new XElement("postalcode", d.postalcode)
)
)
)
);
精彩评论