XmlWriter.WriteAttributeString Method (String, String)

When overridden in a derived class, writes out the attribute with the specified local name and value.

Namespace: System.Xml
Assembly: System.Xml (in system.xml.dll)

public void WriteAttributeString (
	string localName,
	string value
public void WriteAttributeString (
	String localName, 
	String value
public function WriteAttributeString (
	localName : String, 
	value : String



The local name of the attribute.


The value of the attribute.

Exception typeCondition


The state of writer is not WriteState.Element or writer is closed.


The xml:space or xml:lang attribute value is invalid.

WriteAttributeString does the following:

  • If the attribute value includes double or single quotes, they are replaced with " and ' respectively.

  • If writing an xml:space attribute, the writer verifies the attribute value is valid. (Valid values are preserve or default.)

  • If writing an xml:lang attribute, the writer does not verify that the attribute value is valid according to the W3C XML 1.0 recommendation.

The following example writes out a book.

using System;
using System.IO;
using System.Xml;
 public class Sample
   private const string m_Document = "sampledata.xml";
   public static void Main() {
      XmlWriter writer = null;

      try {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        writer = XmlWriter.Create (m_Document);
        writer.WriteComment("sample XML fragment");
        // Write an element (this one is the root).
        // Write the namespace declaration.
        writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");
        // Write the genre attribute.
        writer.WriteAttributeString("genre", "novel");
        // Write the title.
        writer.WriteString("The Handmaid's Tale");
        // Write the price.
        writer.WriteElementString("price", "19.95");
        // Lookup the prefix and write the ISBN element.
        string prefix = writer.LookupPrefix("urn:samples");
        writer.WriteStartElement(prefix, "ISBN", "urn:samples");

        // Write the style element (shows a different way to handle prefixes).
        writer.WriteElementString("style", "urn:samples", "hardcover");
        // Write the close tag for the root element.
        // Write the XML to file and close the writer.

      finally {
        if (writer != null)

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0