Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...