开发者

Is there a faster way to check existence of child elements under the document element of an XML file

开发者 https://www.devze.com 2023-01-12 04:40 出处:网络
I have to analyze a lot of XML files in my current project. I get the XML files asa string object. I wrote a method to check if the XML String contains any data.

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号