c# - Creating complex xml strucure -


i c# developer 1-year experience. facing issue creating complex xml request web service.

i have received xsd file & sample xml requests. i've populate correct data , call web service. 've little experience in creating small xml structures. doing using string concatination /xml document object / xml writer . methodsare small structures bigger structure it's not easy write each , every tags using above object models.

please let me know best way of creating complex xml structures c# . thanks.

linq xml succinct way express xml linq queries.

here how can build xml tree in linq xml (from microsoft: https://msdn.microsoft.com/en-us/library/bb387089.aspx).

xelement contacts = new xelement("contacts",     new xelement("contact",         new xelement("name", "patrick hines"),          new xelement("phone", "206-555-0144"),         new xelement("address",             new xelement("street1", "123 main st"),             new xelement("city", "mercer island"),             new xelement("state", "wa"),             new xelement("postal", "68042")         )     ) ); 

output:

<contacts>   <contact>     <name>patrick hines</name>     <phone>206-555-0144</phone>     <address>       <street1>123 main st</street1>       <city>mercer island</city>       <state>wa</state>       <postal>68042</postal>     </address>   </contact> </contacts> 

joseph albahari's great c# bible c# 5.0 in nutshell has great examples including chapter on "linq xml". free linqpad application comes examples these ones below chapter 10.

the examples below build xml directly linq statements. can see gives more direct control on output xml direct serialization , simplifies creating more complex xml structures.

// query example 1  iqueryable<xelement> sqlquery = c in customers     select          new xelement ("customer", new xattribute ("id", c.id),             new xelement ("name", c.name),             new xelement ("buys", c.purchases.count)         ); var customers = new xelement ("customers", sqlquery);    // query example 2  new xelement ("customers", c in customers     let lastbigbuy = (         p in c.purchases         p.price > 1000         orderby p.date descending         select p     ).firstordefault()     select      new xelement ("customer", new xattribute ("id", c.id),         new xelement ("name", c.name),         new xelement ("buys", c.purchases.count),         new xelement ("lastbigbuy",             new xelement ("description",                 lastbigbuy == null ? null : lastbigbuy.description),             new xelement ("price",                 lastbigbuy == null ? 0m : lastbigbuy.price)             )         )     ) 

Popular posts from this blog