How to iterate through an XDocument's Nodes How to iterate through an XDocument's Nodes xml xml

How to iterate through an XDocument's Nodes


Try this. Not sure why you need the second doc.

foreach (XElement xe in doc.Descendants("Profile")){    MessageBox.Show(xe.Element("username").Value);}


Its easier to use a XPathDocument and a XPath expression.

var doc = new XPathDocument("files\\config.xml")foreach (var username in doc.CreateNavigator().Select("//username"){    ...}


If you are looking for inner node, i.e. recursive like, you can check for the element has element.For example assum you reading your xml from database

string xmlRoot = "select XmlItem from db";XDocument doc = XDocument.Parse(xmlRoot);List<XElement> xElementList = doc.Descendants().ToList();foreach(XElement element in xElementList ){  // read the element and do with your node  if(element.HasElements)    {      // here you can reach nested node    }}