Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...