0

I am trying to figure out how to use Linq to XML to read an XML file into my C# program. Here is the example for my question:

<node name="services" class="tridium.containers.ServiceContainer" module="coreRuntime" release="2.301.532.v1">

How do I access the name, class, module, and release information in this line? I tried .element("node").Name for the name field, but that just returns "node". All of the tutorials I can find are either too simplistic to deal with this, or deal with writing an XML file. Please help.

MatthewHagemann
  • 1,167
  • 2
  • 9
  • 20
  • 1
    See http://msdn.microsoft.com/en-us/library/bb387086.aspx or http://msdn.microsoft.com/en-us/library/bb387070.aspx Note that [`XElement.Name`](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.name%28v=vs.110%29.aspx) returns the name of the **element**, not the attribute `name`. – Mark Rotteveel Jul 03 '14 at 13:35

2 Answers2

3

You can use this :

XElement rootelement = XElement.Load(@"path_to_your_file") ;

var name = rootElement.Attribute("name").Value ; 
var classname = rootElement.Attribute("class").Value ; 
var module = rootElement.Attribute("module").Value ; 
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • 1
    I'm not sure why someone downvoted this. It is exactly what I was looking for. Thank you. (now I see you accidentally put "XmlElement") Don't know why the jerk downvoted instead of simply editing. I will accept this answer. Thanks. – MatthewHagemann Jul 03 '14 at 13:41
  • 1
    Yeah, there was no call to downvote a correct answer, but 5 seconds of reading through the XElement class documentation could've spared you the 10 minutes of waiting for an answer on stackoverflow. – Jakotheshadows Jul 03 '14 at 13:42
  • I didn't downvote, but it is probably because it is a code-only answer; most people prefer some additional explanation or maybe references to more information in answers. – Mark Rotteveel Jul 03 '14 at 13:47
0

If it is at the root, then

XDocument xdoc = XDocument.Load("data.xml");

var name= xdoc.Root.Attribute("name").Value;
var class= xdoc.Root.Attribute("class").Value;
var module= xdoc.Root.Attribute("module").Value;
Steve
  • 2,963
  • 15
  • 61
  • 133