我必须分析我当前项目中的很多XML文件。
我将XML文件作为string
对象获取。
我写了一个方法来检查XML字符串是否包含任何数据。有没有更快的方法来检查XML文件的文档元素下的子元素的存在
private bool ContainsXmlData(string xmlString)
{ 如果(string.IsNullOrEmpty(的xmlString)) 返回false; XmlDocument Doc = new XmlDocument(); 尝试 { Doc.LoadXml(xmlString); } catch(XmlException) { return false; } if(!Doc.DocumentElement.HasChildNodes) return false; 返回true; }
有没有办法更快地执行此检查?是否可以在不使用XmlDocument
的情况下进行检查?
编辑
我已经做了新的方法与XPathDocument
和XPathNavigator
。感谢米奇小麦和Kragen :)
private bool ContainsXmlData(string xmlString)
{ 如果(string.IsNullOrEmpty(的xmlString)) 返回false; 尝试 StringReader Reader = new StringReader(xmlString); XPathDocument doc = new XPathDocument(Reader); XPathNavigator nav = doc.CreateNavigator(); XPathNodeIterator iter = nav.Select(“/”); return(iter.Count> 0)?真假; } catch(XmlException) { return false; } }
贵'xmlString'始终具有相同的根节点?例如' '?或者根可以不同? –
2010-08-20 11:06:04
@DHoerster它可以不同 – peter 2010-08-20 11:14:24