Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an XDocument's Nodes

I am trying to iterate through my xml document's nodes to get the value for <username>Ed</username> in each node. I am using Linq to sort the XDocument first, then attempting to loop through the nodes. I can't seem to find the correct foreach loop to achieve this. Any help is appreciated.

var doc = XDocument.Load("files\\config.xml"); var newDoc = new XDocument(new XElement("Config",             from p in doc.Element("Config").Elements("Profile")             orderby int.Parse(p.Element("order").Value)             select p));   foreach (XElement xe in newDoc.Nodes()) {     MessageBox.Show(xe.Element("username").Value); }  // XML document <Config> <Profile>     <id>Scope</id>     <username>Scope 1</username>     <password>...</password>     <cdkey>0000</cdkey>     <expkey></expkey>     <cdkeyowner>Scope</cdkeyowner>     <client>W2BN</client>     <server>[IP]</server>     <homechannel>Lobby</homechannel>     <load>1</load>     <order>2</order> </Profile> <Profile>     <id>Scope 2</id>     <username>Scope 2</username>     <password>...</password>     <cdkey>0000</cdkey>     <expkey></expkey>     <cdkeyowner>Scope</cdkeyowner>     <client>W2BN</client>     <server>[IP]</server>     <homechannel>Lobby</homechannel>     <load>1</load>     <order>1</order> </Profile> </Config> 
like image 426
Ed R Avatar asked Feb 14 '11 07:02

Ed R


2 Answers

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

foreach (XElement xe in doc.Descendants("Profile")) {     MessageBox.Show(xe.Element("username").Value); } 
like image 64
John Sheehan Avatar answered Sep 24 '22 11:09

John Sheehan


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") {     ... } 
like image 44
Richard Schneider Avatar answered Sep 20 '22 11:09

Richard Schneider