开发者

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

I would like to learn the difference between XMLReader.Create and new XMLTextReader() to read XML. Why woul开发者_Go百科d 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.


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


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'.


For a general answer to why this sort of code esists at all you might want to take a look at the Factory Method Pattern. Using a factory method and an abstract class/interface helps you to write more general code by not tying yourself to a specific implementation. This can help to make your code more easily able to take advantage of new features or to be used in different situations.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜