如何遍历XDocument的节点

我试图遍历我的xml文档的节点,以获取每个节点中Ed的值。 我使用Linq首先对XDocument进行排序,然后尝试遍历节点。 我似乎无法找到正确的foreach循环来实现这一目标。 任何帮助表示赞赏。

 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   Scope Scope 1 ... 0000  Scope W2BN [IP] Lobby 1 2   Scope 2 Scope 2 ... 0000  Scope W2BN [IP] Lobby 1 1   

试试这个。 不确定为什么你需要第二个doc。

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

它更容易使用XPathDocument和XPath表达式。

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

如果你正在寻找内部节点,即递归之类,你可以检查元素是否有元素。 例如,你从数据库中读取xml

 string xmlRoot = "select XmlItem from db"; XDocument doc = XDocument.Parse(xmlRoot); List 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 } }