Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between XMLReader.Create() and new XMLTextReader()

Tags:

c#

xml

I would like to learn the difference between XMLReader.Create and new XMLTextReader() to read XML. Why would I choose one over the other?
Is there a performance difference?

I know XMLReader is an abstract type for XMLTextReader, at least that is what I read before, but I saw somewhere people suggested using XMLReader.Create() methods rather than new XMLReader() instance.

Thanks in advance...

Sincerely.

like image 302
Tarik Avatar asked Oct 11 '09 22:10

Tarik


People also ask

What is the difference between XmlReader and XmlTextReader?

XmlReader is the type you will use to create XML readers. XmlTextReader is one of the many implementations that XmlReader may use based upon what options you specify when creating the reader. Each reader has its own combination of features and abilities.

What is the purpose of IsStartElement () which is instance method of XmlTextReader class?

IsStartElement(String) Calls MoveToContent() and tests if the current content node is a start tag or empty element tag and if the Name property of the element found matches the given argument.

What is XmlTextReader?

XmlTextReader provides forward-only, read-only access to a stream of XML data. The current node refers to the node on which the reader is positioned. The reader is advanced using any of the read methods and properties reflect the value of the current node.


2 Answers

XmlReader.Create allows you to specify XmlReaderSettings, which none of the XmlTextReader constructor overloads do.

like image 60
Jon Skeet Avatar answered Oct 19 '22 06:10

Jon Skeet


Microsoft's answer is simply:

Although the Microsoft .NET Framework includes the XmlTextWriter class, which is an implementation of the XmlWriter class, in the 2.0 release, it is recommended that you use the Create method to create new XmlWriter objects. The Create method allows you to specify the features to support on the created XmlWriter object, and it also allows you to take full advantage of the new features introduced in the 2.0 release.

BUT that answer leaves out the most important difference:

If you call 'new XmlTextReader' it will be set in 'v1compat' mode, which will cause it to have very bad streaming behavior in certain cases, potentially leading to OutOfMemoryExceptions! See Why is my new XmlTextReader(stream) reading in many megabytes into memory rather than streaming properly? for more on that.

RECOMMENDATION: Unless you really need .NET 1.1 behavior, then you should NEVER call 'new XmlTextReader', instead always call 'XmlReader.Create'.

like image 10
Brian Kennedy Avatar answered Oct 19 '22 06:10

Brian Kennedy