2011-12-01 44 views
0

我写了使用的XMLDocumentXMLDOCUMENT等值的XDocument

string Query = @"/ShortcutList/" + Modality; 
      XmlNodeList nodes = shortcutsXMLDocument.SelectNodes(Query); 
      if (nodes == null) 
      { 
       // if the modality not exists, I will load the Default one 

       Query = @"/ShortcutList/Default"; 
       nodes = shortcutsXMLDocument.SelectNodes(Query); 
      } 

      for (int i = 0; i < nodes[0].ChildNodes.Count; i++) 
      { 
// do something here 
} 

其中shortcutsXMLDocument是为XMLDocument

下面的代码

如何使用的XDocument它转换,我没能找到相当于的SelectNodes中的XDocument

任何想法请

回答

1

那么代码是相当奇怪的SelectNodes总是返回一个XmlNodeList所以检查if (nodes == null)永远不会是真的,你也可以删除它。 至于前两行,你可以用

List<XElement> nodes = shortcutsXMLDocument.Elements("ShortcutList").Elements(Modality).ToList(); 

假设Modality变量只包含一个元素的名称,而不是一个完整的XPath表达式替换它们。

然后,对于for循环,您可以使用例如,

foreach (XNode node in nodes[0].Nodes()) { 
    // do something here with node 
} 

,但我怀疑,如果你告诉我们你想要通过张贴XML的样品和数据的要提取一些解释,以实现我们可以写更清晰和简单的代码。