Writing Attributes
Collapse the table of content
Expand the table of content
The document is archived and information here might be outdated

Writing Attributes 

The WriteAttributeString, WriteStartAttribute, and WriteAttributes methods are designed specifically for attribute creation. With these methods, you can write attributes on element or XML declaration nodes. The write attribute methods can also be used to create namespace declarations on an element. See Namespace Handling in the XmlWriter to learn more about namespaces.


The WriteAttributeString method is the simplest way to write an attribute. It is used to write an entire attribute node, including a string value. The following code writes out the supplierID='A23-1' XML string.

writer.WriteAttributeString("supplierID", "A23-1");


The WriteStartAttribute method is a more advanced version of the WriteAttributeString method. It allows you to write the attribute value using multiple method calls. For example, you can use WriteValue to write a typed value.

The attribute is closed by calling the WriteEndAttribute method.

In the following code, hireDate is a DateTime object that holds an employee hiring date. The code writes a review-date attribute, which contains the calculated value of the employee 6-month review date.



The WriteAttributes method allows you to copy all the attributes found at the current position of the supplied XmlReader object. The WriteAttributes behavior depends on the type of node the reader is currently positioned on.

The following table describes the results of calling WriteAttributes for each node type. If the reader is positioned on a node type that is not listed in the table below, WriteAttributes has no operation.

Node type WriteAttributes behavior


Writes the current attribute, then the rest of the attributes until the element closing tag.


Writes all attributes contained by the element.

XML Declaration

Writes all the attributes in the declaration.

For example, in the following code, the writer copies all attributes found at the current position of the reader to the writer.

writer.WriteAttributes(reader, true);

If the reader were positioned on an element with three attributes, the following XML string is written.

<root genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0" />

See Also

© 2016 Microsoft