XElement有类似的XmlNodeList

sen*_*ale 3 c# xml

我想用XElement做这个:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

mlNodeList nodeList = doc.GetElementsByTagName("Title");
Run Code Online (Sandbox Code Playgroud)

并获得所有节点.可能吗?

Mik*_*ron 6

相当于您的代码是:

XElement doc = XElement.Parse(xml);
IEnumerable<XElement> nodeList = doc.Descendants("Title");
Run Code Online (Sandbox Code Playgroud)

nodeList.ToList()如果你需要一个离散列表,你可以打电话,但如果你只是想迭代,那IEnumerable应该没问题.

编辑:有两种方法可以选择节点.使用Elements(),如果你需要一个节点的直接孩子,或使用Descendants(),如果你需要的所有的孩子,无论他们有多么深.