c# - Complex type mapping via linq to xml -
i have list of contacts in xml file.
each contact have few properties , mdpr:connection
in it.
connection separate object.
read list , contacts list standard proeprties how map connection object.
<?xml version="1.0" encoding="utf-8"?> <mdpr:data xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:mdpr="http://..."> <mdpr:contactlist> <mdpr:contact id="{123456}" classid="customer"> <mdpr:name>data1</mdpr:name> <mdpr:transportcode>data2</mdpr:transportcode> <mdpr:connection connectionindex="0" fromid="{12345}" toid="{123456}"> <mdpr:status>1-5</mdpr:status> <mdpr:startdate>2012-03-13t10:23:00z</mdpr:startdate> <mdpr:enddate>2013-03-13t13:44:00z</mdpr:enddate> </mdpr:connection> </mdpr:contact> </mdpr:contactlist> ... classes: public class contact { public string name { get; set; } public string transportcode { get; set; } public connection connection { get; set; } public transportplan() { this.connection = new connection(); } } public class connection { public string status{ get; set; } public string startdate{ get; set; } public string enddate { get; set; } }
code read data:
xnamespace mdpr = "http://..."; var contacts = c in xdoc.root.element(mdpr + "contactlist") .elements(mdpr + "contact") select new contact { transportcode = (string)c.element(mdpr + "transportcode"), name = (string)c.element(mdpr + "name") };
so question how read mdpr:connection
?
you can access elements directly adding '.element'. added variable better readability.
var contacts = c in xdoc.element(mdpr + "data") .element(mdpr + "contactlist") .elements(mdpr + "contact") let contact = c let connection = contact.element(mdpr + "connection") select new contact { transportcode = (string)contact.element(mdpr + "transportcode"), name = (string)contact.element(mdpr + "name"), connection = new connection { status = (string)connection.element(mdpr + "status"), startdate = (string) connection.element(mdpr + "startdate"), enddate = (string)connection.element(mdpr + "enddate"), }, };
if want allow multiple connections (in order make scenario more complex)
public class contact { public string name { get; set; } public string transportcode { get; set; } public list<connection> connections { get; set; } }
code parse multiple connections
var contacts = c in xdoc.element(mdpr + "data") .element(mdpr + "contactlist") .elements(mdpr + "contact") let contact = c let connections = contact.elements(mdpr + "connection") select new contact { transportcode = (string)contact.element(mdpr + "transportcode"), name = (string)contact.element(mdpr + "name"), connections = connections.select( connection => new connection { status = (string)connection.element(mdpr + "status"), startdate = (string) connection.element(mdpr + "startdate"), enddate = (string)connection.element(mdpr + "enddate"), }).tolist(), };
Comments
Post a Comment