dimanche 10 mai 2015

Multilevel XML ForEach WPF

I need to get the values from many nodes in a XML that is a few levels deep.

Valid XML Sample

<?xml version="1.0" encoding="UTF-8"?>
 <server>
  <id>245723</id>
  <name>Server Name</name>
  <host>IP Address</host>
  <port>Port</port>
   <servertype>
    <type>Linux</type>
    <cpu>Linux</cpu>
     <connections>
       <connection>
         <id>1234</id>
         <con_type>new</con_type> 
       </connection>
       <connection>
         <id>565665</id>
         <con_type>new</con_type> 
       </connection>
       <connection>
         <id>908546546466</id>
         <con_type>old</con_type> 
       </connection>
     </connections>
    </servertype>
   </server>

So basically I need to access and run through a foreach inside the connections node. I have used the below code to get the first level nodes values (each node) into a listbox. Works well.

C# Code for reading XML

string urlAddress = "url to xml file on server";
XDocument itemz = XDocument.Load(urlAddress);

foreach (var item in itemz.Descendants("server"))
{
    string name = item.Element("id").Value;

    //adding value to a listbox (sample)
    lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);
}

Is there a way to use the same code(as such) to get each item(value) under the connections nodes. So something like flow example below

  server> servertype > connections > foreach connection > get values of connection

would it require something like

foreach (var item in itemz.Descendants("server")) {

    foreach (var item in itemz.Descendants("connections"))  {

        //foreach connection
        foreach (var item in itemz.Descendants("connection")) {

            //add connection id to listbox 
            lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire