XElement to get all sub-element node names and values

Loser Coder picture Loser Coder · Nov 25, 2010 · Viewed 19.9k times · Source

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!

Answer

Tim Jarvis picture Tim Jarvis · Nov 25, 2010

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.