peter
peter

Reputation: 563

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 a string 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; } }

Upvotes: 1

Views: 926

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300489

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.

Upvotes: 3

Related Questions