System.Xml.XmlWriter class

The XmlWriter class writes XML data to a stream, file, text reader, or string. It supports the W3C Extensible Markup Language (XML) 1.0 (fourth edition) and Namespaces in XML 1.0 (third edition) recommendations.

The members of the XmlWriter class enable you to:

  • Verify that the characters are legal XML characters and that element and attribute names are valid XML names.
  • Verify that the XML document is well-formed.
  • Encode binary bytes as Base64 or BinHex, and write out the resulting text.
  • Pass values by using common language runtime types instead of strings, to avoid having to manually perform value conversions.
  • Write multiple documents to one output stream.
  • Write valid names, qualified names, and name tokens.

Create an XML writer

To create an XmlWriter instance, use the XmlWriter.Create method. To specify the set of features you want to enable on the XML writer, pass an XmlWriterSettings to the Create method. Otherwise, default settings are used. See the Create reference pages for details.

Specify the output format

The XmlWriterSettings class includes several properties that control how XmlWriter output is formatted:

Property Description
Encoding Specifies the text encoding to use. The default is Encoding.UTF8.
Indent Indicates whether to indent elements. The default is false (no indentation).
IndentChars Specifies the character string to use when indenting. The default is two spaces.
NewLineChars Specifies the character string to use for line breaks. The default is \r\n (carriage return, line feed) for non-Unix platforms, and \n (line feed) for Unix platforms.
NewLineHandling Specifies how to handle newline characters.
NewLineOnAttributes Indicates whether to write attributes on a new line. Indent should be set to true when using this property. The default is false.
OmitXmlDeclaration Indicates whether to write an XML declaration. The default is false.

The Indent and IndentChars properties control how insignificant white space is formatted. For example, to indent element nodes:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create("books.xml", settings);
Dim settings As New XmlWriterSettings()
settings.Indent = True
settings.IndentChars = vbTab
Dim writer As XmlWriter = XmlWriter.Create("books.xml", settings)

Use the NewLineOnAttributes to write each attribute on a new line with one extra level of indentation:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineOnAttributes = true;
XmlWriter writer = XmlWriter.Create("books.xml", settings);
Dim settings As New XmlWriterSettings()
settings.Indent = True
settings.NewLineOnAttributes = True
Dim writer As XmlWriter = XmlWriter.Create("books.xml", settings)

Data conformance

An XML writer uses two properties from the XmlWriterSettings class to check for data conformance:

  • The CheckCharacters property instructs the XML writer to check characters and throw an XmlException exception if any characters are outside the legal range, as defined by the W3C.

  • The ConformanceLevel property configures the XML writer to check that the stream being written complies with the rules for a well-formed XML 1.0 document or document fragment, as defined by the W3C. The three conformance levels are described in the following table. The default is Document. For details, see the XmlWriterSettings.ConformanceLevel property and the System.Xml.ConformanceLevel enumeration.

    Level Description
    Document The XML output conforms to the rules for a well-formed XML 1.0 document and can be processed by any conforming processor.
    Fragment The XML output conforms to the rules for a well-formed XML 1.0 document fragment.
    Auto The XML writer determines which level of conformation checking to apply (document or fragment) based on the incoming data.

Write elements

You can use the following XmlWriter methods to write element nodes. For examples, see the methods listed.

Use To
WriteElementString Write an entire element node, including a string value.
WriteStartElement To write an element value by using multiple method calls. For example, you can call WriteValue to write a typed value, WriteCharEntity to write a character entity, WriteAttributeString to write an attribute, or you can write a child element. This is a more sophisticated version of the WriteElementString method.

To close the element, you call the WriteEndElement or WriteFullEndElement method.
WriteNode To copy an element node found at the current position of an XmlReader or XPathNavigator object. When called, it copies everything from the source object to the XmlWriter instance.

Write attributes

You can use the following XmlWriter methods to write attributes on element nodes. These methods can also be used to create namespace declarations on an element, as discussed in the next section.

Use To
WriteAttributeString To write an entire attribute node, including a string value.
WriteStartAttribute To write the attribute value using multiple method calls. For example, you can call WriteValue to write a typed value. This is a more sophisticated version of the WriteElementString method.

To close the element, you call the WriteEndAttribute method.
WriteAttributes To copy all the attributes found at the current position of an XmlReader object. The attributes that are written depend on the type of node the reader is currently positioned on:

- For an attribute node, it writes the current attribute, and then the rest of the attributes until the element closing tag.
- For an element node, it writes all attributes contained by the element.
- For an XML declaration node, it writes all the attributes in the declaration.
- For all other node types, the method throws an exception.

Handle namespaces

Namespaces are used to qualify element and attribute names in an XML document. Namespace prefixes associate elements and attributes with namespaces, which are in turn associated with URI references. Namespaces create element and attribute name uniqueness in an XML document.

The XmlWriter maintains a namespace stack that corresponds to all the namespaces defined in the current namespace scope. When writing elements and attributes you can utilize namespaces in the following ways:

  • Declare namespaces manually by using the WriteAttributeString method. This can be useful when you know how to best optimize the number of namespace declarations. For an example, see the WriteAttributeString(String, String, String, String) method.

  • Override the current namespace declaration with a new namespace. In the following code, the WriteAttributeString method changes the namespace URI for the "x" prefix from "123" to "abc".

    writer.WriteStartElement("x", "root", "123");
    writer.WriteStartElement("item");
    writer.WriteAttributeString("xmlns", "x", null, "abc");
    writer.WriteEndElement();
    writer.WriteEndElement();
    
    writer.WriteStartElement("x", "root", "123")
    writer.WriteStartElement("item")
    writer.WriteAttributeString("xmlns", "x", Nothing, "abc")
    writer.WriteEndElement()
    writer.WriteEndElement()
    

    The code generates the following XML string:

    <x:root xmlns:x="123">
      <item xmlns:x="abc" />
    </x:root>
    
  • Specify a namespace prefix when writing attributes or elements. Many of the methods used to write element and attributes enable you to do this. For example, the WriteStartElement(String, String, String) method writes a start tag and associates it with a specified namespace and prefix.

Write typed data

The WriteValue method accepts a common language runtime (CLR) object, converts the input value to its string representation according to XML schema definition language (XSD) data type conversion rules, and writes it out by using the WriteString method. This is easier than using the methods in the XmlConvert class to convert the typed data to a string value before writing it out.

When writing to text, the typed value is serialized to text by using the XmlConvert rules for that schema type.

For default XSD data types that correspond to CLR types, see the WriteValue method.

The XmlWriter can also be used to write to an XML data store. For example, the XPathNavigator class can create an XmlWriter object to create nodes for an XmlDocument object. If the data store has schema information available to it, the WriteValue method throws an exception if you try to convert to a type that is not allowed. If the data store does not have schema information available to it, the WriteValue method treats all values as an xsd:anySimpleType type.

Close the XML writer

When you use XmlWriter methods to output XML, the elements and attributes are not written until you call the Close method. For example, if you are using XmlWriter to populate an XmlDocument object, you won't be able to see the written elements and attributes in the target document until you close the XmlWriter instance.

Asynchronous programming

Most of the XmlWriter methods have asynchronous counterparts that have "Async" at the end of their method names. For example, the asynchronous equivalent of WriteAttributeString is WriteAttributeStringAsync.

For the WriteValue method, which doesn't have an asynchronous counterpart, convert the return value to a string and use the WriteStringAsync method instead.

Security considerations

Consider the following when working with the XmlWriter class:

  • Exceptions thrown by the XmlWriter can disclose path information that you do not want bubbled up to the app. Your app must catch exceptions and process them appropriately.

  • XmlWriter does not validate any data that is passed to the WriteDocType or WriteRaw method. You should not pass arbitrary data to these methods.