1
votes

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

1
Does your xmlString always have the same root node? e.g., <myRoot></myRoot>? Or can the root be different? - David Hoerster
@DHoerster It can be different - peter

1 Answers

3
votes

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.