Is there a faster way to check existence of child elements under the document element of an XML file
I have to analyze a lot of XML files in my current project.
I get the XML files as astring
object.
I wrote a method to check if the XML String contains any data.
private bool ContainsXmlData(string xmlString)
{ if (string.IsNullOrEmpty(xmlString)) return false; XmlDocument Doc = new XmlDocument(); try { Doc.LoadXml(xmlString); } catch (XmlException) { return false; } if (!Doc.DocumentElement.HasChildNodes) return false; return true; }
Is there a way to perform this check faster? Is it possible to check this without using an XmlDocument
?
EDIT
I have made a new method with XPathDocument
and XPathNavigator
. Thanks Mitch Wheat and Kragen :)
private bool ContainsXmlData(string xmlString)
{ if (string.IsNullOrEmpty(xmlString)) return false; try { StringReader Reader = new StringReader(xmlString); XPathDocument doc = new XPathDocument(Reader); XPathNavigator 开发者_如何学编程nav = doc.CreateNavigator(); XPathNodeIterator iter = nav.Select("/"); return (iter.Count > 0) ? true : false; } catch (XmlException) { return false; } }
XPathDocument provides fast, read-only access to the contents of an XML document using XPath.
Or use an XmlTextReader (fastest) which provides fast, forward-only, non-cached access to XML data.
- At-A-Glance: XmlReader vs. XPathNavigator vs. XmlDocument
精彩评论