Search code examples
c#xmlwindows-phone-7xelement

Get names of XElements


I'm parsing xml in the app for windows phone. My XML Looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<people>
    <person name="Kurt Cobain">
      <overall>
  
      </overall>
      <childhood>
  
      </childhood>
      <youth>
  
      </youth>
  
     <picture1>
  
      </picture1>
    </person>
  
</people>

I should get the names of the element of the person node(overall, childhood, youth etc) because for each person node they will be different. Here is my code so far,but the query results in null:

XDocument loadedXml = XDocument.Load("people.xml");

                    var data = from query in loadedXml.Descendants("person")
                               where ((query.Attribute("name").Value as string).Equals("Kurt Cobain"))
                               select query.Elements();

                    
                     string test = "";
                     foreach (var item in data)
                     {
                         
                             test + = (item as XElement).Name.LocalName;
                         
                     }
                     MessageBox.Show(test);

Solution

  • Remove .Elements() from your linq.

    var data = from query in loadedXml.Descendants("person") 
               where ((query.Attribute("name").Value as string).Equals("Kurt Cobain")) 
               select query;