How to Get Element Names from XElement Using C#?

Aravind Srinivas picture Aravind Srinivas · Mar 11, 2013 · Viewed 14k times · Source

I have a Xml and i have to get the element name

 <Data>
     <Test key="G" modifier="control" /> 
     <Test1  key="E" modifier="control" /> 
     <Test3 /> 
     <Test4 /> 
 </Data>

 XDocument xd = XDocument.Load("..\\Cmd.xml");
 IEnumerable<XElement> xeCmdData = Cmd.XPathSelectElements(".//Data");

 foreach (XElement xeData in xeCmdData)
 {
     // here i am getting the whole xml how to get Element name  ... 
     // Like <Data> 
     //          <Test key="G" modifier="control" /> 
     //          <Test1  key="E" modifier="control" /> 
     //          <Test3 /> 
     //          <Test4 />  
     //      </Data>
 }               

How to get Element names ?

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Mar 11, 2013
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<string> names = xd.XPathSelectElements("//Data/*")      
                              .Select(e => e.Name.LocalName);

Or without XPath

IEnumerable<string> names = xd.Descendants("Data")      
                              .Elements()
                              .Select(e => e.Name.LocalName);

Result:

Test
Test1
Test3
Test4