Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Element Names from XElement Using C#?

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 ?

like image 238
Aravind Srinivas Avatar asked Mar 11 '13 10:03

Aravind Srinivas


1 Answers

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
like image 73
Sergey Berezovskiy Avatar answered Sep 21 '22 13:09

Sergey Berezovskiy