如何迭代XDocument的節點

[英]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.

我嘗試遍歷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
<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>

3 个解决方案

#1


40  

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

試試這個。不知道為什么需要第二個醫生。

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

#2


4  

Its easier to use a XPathDocument and a XPath expression.

使用XPathDocument和XPath表達式更容易。

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

#3


1  

If you are looking for inner node, i.e. recursive like, you can check for the element has element. For example assum you reading your xml from database

如果您正在尋找內部節點,例如遞歸,您可以檢查元素是否有元素。例如,當您從數據庫中讀取xml時

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

} 

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/02/14/7210e4f8f223702d923fa71561f9f02e.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com