Efficient way to build an XML document from a string containing well-formed XML for navigation?

I have a string containing well formed xml in it. I want to navigate XML in this line to extract text in specific nodes. How to effectively accomplish this with the built-in .NET class. Which .NET XML class would you use and why?

Many thanks for your help.

Note 1: Linq is not available to me. Note 2: XML editing is not important. Read-only access is what I need.

+6
c # xml
source share
4 answers

For speed use XmlReader :

 using (StringReader sr = new StringReader(myString)) using (XmlReader xr = XmlReader.Create(sr)) { while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && xr.Name == "foo") { Console.WriteLine(xr.ReadString()); } } } 

The above displays the text content of each element named "foo" in the XML document. (Well, sort of. ReadString doesn't handle nested elements very well.)

Using XPathDocument is slower because the whole document is parsed before you can start it, but it has the virtue of simplicity:

 using (StringReader sr = new StringReader(myString)) { XPathDocument d = new XPathDocument(sr); foreach (XPathNavigator n in d.CreateNavigator().Select("//foo/text()")) { Console.WriteLine(n.Value); } } 

If you are not interested in performance or memory usage, try using XmlDocument :

 XmlDocument d = new XmlDocument(); d.LoadXml(myString); foreach (XmlNode n in d.SelectNodes("//foo/text()")) { Console.WriteLine(n.Value); } 
+10
source share

For navigation? Probably XPathDocument :

 string s = @"<xml/>"; XPathDocument doc = new XPathDocument(new StringReader(s)); 

From MSDN,

Provides a fast, read-only, in-memory representation of an XML document using the XPath data model.

Unlike XmlDocument , etc., it is optimized for read-only use; more efficient but less powerful (i.e. you cannot edit it). For notes on how to request it, see here .

+7
source share

I would use XmlDocument.Load () to get the DOM from the string. You can then traverse it using the appropriate DOM or XPATH methods as needed.

+3
source share

It depends on the structure of the XML. If it's relatively simple, then the most efficient way to wrap a string in StringReader and then wrap it in XmlReader . The advantage is that you do not need to create an XML tree in memory by copying data from a string - you will just read the nodes one by one.

If the structure of the document is quite complex, you may need (or need) a DOM - in this case XDocument.Parse should do the trick.

+3
source share

All Articles