开发者

XElement to get all sub-element node names and values

开发者 https://www.devze.com 2023-01-27 08:15 出处:网络
I\'m thinking of an approach something like this. Please let me know if this can actually work this way:

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 ...
        开发者_StackOverflow中文版  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!


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.


Haven't made a use of it yet but LINQ to XML looks like all kinds of awesome. Here are some links. MSDN Reference Hooked On LINQ


use http://msdn.microsoft.com/de-de/library/bb342765.aspx to get all children and http://msdn.microsoft.com/de-de/library/system.xml.linq.xelement.name.aspx to check for the name.

0

精彩评论

暂无评论...
验证码 换一张
取 消