LINQ to XML, with conditions and Variable XML Structure with C# -


i have big issue, , lost 5 hours on it. have create xml file, populated database reg. have variable structure, in cases use specific sub structure.

the logic simple.

i have agencys, in every agency have iterate foreach cycle, , houses whant sell/rent. not houses, there´s apartaments, garages, , on. each of scenes have own structure different data.

this not all, there must have condition. writes xml childs if supposed to.

piece of xml example

<clients>     <client>         <aggregator/>         <code/>         <reference/>         <contact>         <secondhandlisting>             <property>                 <code/>                 <reference/>                 <scope/>                 <address>                 <features/>                 <operation>     // variable structure      1example        <price/>                     <communitycosts/>      2example       <price/>                    <communitycosts/>                    <deposittype/>                  </operation>             </property>         </secondhandlisting> 

can 1 show me example of how done. archive until was:

var agenciasconectores = //query of agencys  foreach (var agenciaconector in agenciasconectores) {     var imoveisagencia = // query of homes in each agency      xdocument doc = new xdocument(         new xdeclaration("1.0", "utf-8", "yes"),         new xelement("clients",             agencia in agenciasconectores                 select new xelement("client", new xattribute("id", agencia.agencyid),                 new xelement("aggregator", agencia.connectorlicense),                 new xelement("code", agencia.name),                 new xelement("reference", agencia.phone),                 new xelement("contact", agencia.phone),                 new xelement("secondhandlisting"),                 new xelement("newbuildlisting")                 )));     foreach (var imovel in imoveisagencia)     {         if (imoveisagencia.count() > 1)         {             doc.document.add(new xelement("property",                 new xelement("code", "codigo"),                 new xelement("reference", "reference"),                 new xelement("scope", "scope"),                 new xelement("address", "address"),                 new xelement("contact", "contact"),                 new xelement("features", "features"),                 new xelement("operation", "operation"),                 new xelement("description", "description")));         }      }  } 

when try run in visual studio, following line throws exception

doc.document.add(new xelement("property", ... 

are trying more this?

doc.root.add(new xelement("property", ... 

or, perhaps, closer this

doc.descendants("client")     .single(c => c.code == "something")     .add(new xelement("property",     ... 

Comments