使用linq to xml遍历xml树中的每个元素

问题描述:

我想遍历xml中的每个元素和属性,并在不知道元素名称的情况下提取一个值的名称。我甚至有一本关于使用C#编写linq to xml的书,它只告诉我如何查询元素的值,以便知道元素的名称。使用linq to xml遍历xml树中的每个元素

下面的代码只给我最高级别的元素信息。我还需要达到所有降序要素。

  XElement reportElements = null; 
      reportElements = XElement.Load(filePathName.ToString()); 


      foreach (XElement xe in reportElements.Elements()) 
      { 

       MessageBox.Show(xe.ToString()); 
      } 

Elements只走一个级别; Descendants遍历整个DOM的元素,那么你就可以(每件)检查属性:

foreach (var el in doc.Descendants()) { 
     Console.WriteLine(el.Name); 
     foreach (var attrib in el.Attributes()) { 
      Console.WriteLine("> " + attrib.Name + " = " + attrib.Value); 
     } 
    } 
+0

这真是棒极了!非常感谢您的帮助! – 2009-11-15 21:40:23

+0

JK - 忘记了什么? – 2009-11-17 04:58:05

+0

呃,我不知道你忘了什么是什么意思。 – 2009-11-17 06:57:55

你应该尝试:

reportElements.Descendants()