LINQ - How to traverse each and every element from and existing xml

Asked By test123 Murugan on 12-Feb-12 02:50 AM
The following xml is my input xml. how can read each and every element through LINQ. Since its different set of elements difficult to travers me in LINQ..Also i am the new to the LINQ development..Need help from someone..how to retrive in LINQ like each list of objects

<PoweredPNR_AddMultiElements>

<reservationInfo>

<reservation>

<controlNumber>479GC4</controlNumber>

</reservation>

</reservationInfo>

<pnrActions>

<optionCode>0</optionCode>

</pnrActions>

<dataElementsMaster>

<marker1/>

<dataElementsIndiv>

<elementManagementData>

<segmentName>FP</segmentName>

</elementManagementData>

<formOfPayment>

<fop>

<identification>CC</identification>

<amount>1000</amount>

<creditCardCode>VI</creditCardCode>

<accountNumber>4324383499030519</accountNumber>

<expiryDate>1212</expiryDate>

<approvalCode>123</approvalCode>

<currencyCode>QAR</currencyCode>

</fop>

</formOfPayment>

<fopExtension>

<fopSequenceNumber>1</fopSequenceNumber>

<newFopsDetails>

<cvData>610</cvData>

</newFopsDetails>

</fopExtension>

</dataElementsIndiv>

<dataElementsIndiv>

<elementManagementData>

<segmentName>RF</segmentName>

</elementManagementData>

<freetextData>

<freetextDetail>

<subjectQualifier>3</subjectQualifier>

</freetextDetail>

<longFreetext>IVR</longFreetext>

</freetextData>

</dataElementsIndiv>

</dataElementsMaster>

</PoweredPNR_AddMultiElements>

D Company replied to test123 Murugan on 12-Feb-12 03:03 AM
Hello Friend,

Simply use foreach loop to traverse through each element.
foreach (XElement somename in element.Descendants("filename"))
                {
              fo
reach (XElement item in n.Descendants())
                   
{
                       
//get value of all child nodes for your file
} }

for more detail visit MSDN site having good examples
Regards
D
D Company replied to test123 Murugan on 12-Feb-12 03:16 AM
there is one more simple way to retrieve all elements,like this

XDocument nameofDoc= new XDocument("path");
foreach (var xelem  in contact.Elements()) 
{
 Console.WriteLine(xelem.Name().ToString());  }


Hope it helps!!
Regards
D
kalpana aparnathi replied to test123 Murugan on 12-Feb-12 04:42 AM
hi,

Try this below code for traverse each and every element from and existing XML

foreach (var element in doc.Descendants()) {
    Console.WriteLine(element.Name);
    foreach (var attribute in element.Attributes()) {
      Console.WriteLine("> " + attribute.Name + " = " + attribute.Value);
    }
  }