I am looking at these these two classes in C#: XmlTextWriter
and XmlWriter
.
Can anyone explain the difference and tell me where to use which?
Asked
Active
Viewed 1.9k times
29

Marcel
- 15,039
- 20
- 92
- 150

Muhammad Basit
- 291
- 1
- 3
- 3
-
3Well, first off, you can't instantiate `XmlWriter`. – BoltClock Aug 01 '11 at 13:56
-
1@BoltClock Hm, technically yes, but it has a static `Create()` method which creates an instance. Doesn't that count? – Marcel Sep 17 '14 at 06:10
-
2@Marcel: You can only create an instance of a subclass. You can't do `new XmlWriter` because it's abstract. – BoltClock Sep 17 '14 at 06:11
-
1@BoltClock I just called `XmlWriter.Create(stream, settings)` right now and it gives me an `XmlWriter`. It's also described exactly to do so in the docs: http://msdn.microsoft.com/en-us/library/ms162617%28v=vs.110%29.aspx – Marcel Sep 17 '14 at 06:18
-
1@Marcel: What does `GetType()` on that instance return? – BoltClock Sep 17 '14 at 06:19
-
1@BoltClock In my case, it's a `XmlWellFormedWriter`. You get the point. – Marcel Sep 17 '14 at 06:25
1 Answers
32
XmlWriter
is an abstract class.
XmlTextWriter
is a specific implementation of XmlWriter
.
You should always call XmlWriter.Create
.
MSDN says:
In the .NET Framework version 2.0 release, the recommended practice is to create XmlWriter instances using the XmlWriter.Create method and the XmlWriterSettings class. This allows you to take full advantage of all the new features introduced in this release. For more information, see Creating XML Writers.
-
1"You should always call XmlWriter.Create" why do you make this assertion ? – Steve B Aug 01 '11 at 13:58
-
5
-
1Too bad `XmlWriter` and `XmlWriterSettings` miss a `QuoteChar` property which `XmlTextWriter` has, rendering them useless if you require (for whatever reasons) 'single-quoted' attributes instead of the "double-quoted" ones. – Ray Oct 25 '19 at 14:11