Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement to get all sub-element node names and values

I'm thinking of an approach something like this. Please let me know if this can actually work this way: For Sample XML:

<Root>
  <Node>
    <SubEl1>abc</SubEl1>
    <SubEl2>def</SubEl2>
    <SubEl3>123</SubEl3>
    <SubEl4>456</SubEl4>      
  </Node>
</Root>

Want to go into <Node>, loop through check for the node/element name and get it's value. Something like this, say name is 'SubEl1' use 'abc' for task1, on seeing the element name is 'SubEl2' I do task2. All sub-elements have to be checked for!

Example (not working code):

 //looping through 'Node' children
        switch(SubElName for 'Node element) 
        {
          case : 'SubEl1' 
            //Do Task1 using the SubEl1's value/TextName ...
          case: 'SubEl2' 
           //Task2 ...
          ... 
          case: default //Do default task.....
        } 
    //end loop

If you can think of any other approach (XElement, XmlDocument, SelectNodes() etc., that will be appreciated too!

like image 652
Loser Coder Avatar asked Nov 24 '10 23:11

Loser Coder


1 Answers

For this task it looks like all you need to do is simply create a list/dictionary of the node name and the node value, you then can use that in your switch....

var list = from x in XElement.Load(**yourxmlfile**).Element("Node").Elements()
           select new
           {
              Name = x.Name,
              Value = (string)x
           };

now you have a list of Name, value pairs you can simply pass to your switch method.

like image 117
Tim Jarvis Avatar answered Nov 09 '22 13:11

Tim Jarvis