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>
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With