读取具有未知根/父节点的XML节点时出现问题

我一直在尝试读取xml文件。 我必须提取节点“Date”和“Name”的值,但问题是,它们可能出现在XML层次结构中的任何级别。

所以,当我尝试使用此代码时,

XmlDocument doc = new XmlDocument(); doc.Load("test1.xml"); XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("//*"); string date; string name; foreach (XmlNode node in nodes) { date = node["date"].InnerText; name = node["name"].InnerText; } 

和XML文件是::

    Aravind 12/03/2000   

上面的代码错误输出,因为不是root的直接子元素。
是否有可能假设父/根节点是未知的,只是用节点的名称,复制值?

根据您获得的例外情况,这可能是也可能不是确切的解决方案。 但是,在对它们执行.InnerText之前,我肯定会检查datename存在。

  foreach (XmlNode node in nodes) { dateNode = node["date"]; if(dateNode != null) date = dateNode.InnerText; // etc. } 

我会读到XPath和XPath for C#来更有效地完成这项工作

http://support.microsoft.com/kb/308333

http://www.w3schools.com/XPath/xpath_syntax.asp

这里有一个方法可以让你轻松获得innerText。

 function string GetElementText(string xml, string node) { XPathDocument doc = new XPathDocument(xml); XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr = nav.Compile("//" + node); XPathNodeIterator iterator = nav.Select(expr); while (iterator.MoveNext()) { // return 1st but there could be more return iterator.Current.Value; } } 

尝试使用LINQ:

  string xml = @"  12/03/2001  Aravind 12/03/2000  AS-CII "; XDocument doc = XDocument.Parse(xml); foreach (var date in doc.Descendants("date")) { Console.WriteLine(date.Value); } foreach (var date in doc.Descendants("name")) { Console.WriteLine(date.Value); } Console.ReadLine(); 

Descendants方法允许您获取具有指定名称的所有元素。