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

后端 未结 3 548
难免孤独
难免孤独 2021-01-04 06:32

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 th

相关标签:
3条回答
  • 2021-01-04 06:35

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

    0 讨论(0)
  • 2021-01-04 06:40

    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 讨论(0)
  • 2021-01-04 06:56

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

    0 讨论(0)
提交回复
热议问题