System.Xml.XmlTextWriter Class

Assembly: System.Xml.dll
Namespace: System.Xml
Summary
Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.
C# Syntax:
public class XmlTextWriter : XmlWriter
Remarks
This class implements the XmlWriter class.

XmlTextWriter maintains a namespace stack corresponding to all the namespaces defined in the current element stack. Using XmlTextWriter you can declare namespaces manually.

          w.WriteStartElement("root");
          w.WriteAttributeString("xmlns", "x", null, "urn:1");
           w.WriteStartElement("item","urn:1");
           w.WriteEndElement();
           w.WriteStartElement("item","urn:1");
           w.WriteEndElement();
          w.WriteEndElement();
        

The above C# code produces the following output.XmlTextWriter promotes the namespace declaration to the root element to avoid having it duplicated on the two child elements. The child elements pick up the prefix from the namespace declaration.

          <root xmlns:x="urn:1">
           <x:item/>
           <x:item/>
          </x:root>
        

XmlTextWriter also allows you to override the current namespace declaration. In the following example the namespace URI "123" is overridden by "bar" to produce the XML element <x:node xmlns:x="bar"/> .

          w.WriteStartElement("x","node","123");
          w.WriteAttributeString("xmlns","x",null,"bar");
        
By using the write methods that take a prefix as an argument you can also specify which prefix to use. In the following example, two different prefixes are mapped to the same namespace URI to produce the XML text <x:root xmlns:x="urn:1"><y:item xmlns:y="urn:1"/></x:root> .
          XmlTextWriter w = new XmlTextWriter(Console.Out);
          w.WriteStartElement("x","root","urn:1");
           w.WriteStartElement("y","item","urn:1");
           w.WriteEndElement();
          w.WriteEndElement();
          w.Close();
        

If there are multiple namespace declarations mapping different prefixes to the same namespace URI, XmlTextWriter walks the stack of namespace declarations backwards and picks the closest one.

          XmlTextWriter w = new XmlTextWriter(Console.Out);
          w.Formatting = Formatting.Indented;
          w.WriteStartElement("x","root","urn:1");
          w.WriteStartElement("y","item","urn:1");
          w.WriteAttributeString("attr","urn:1","123");
          w.WriteEndElement();
          w.WriteEndElement();
          w.Close();
        

In the above C# example, because the WriteAttributeString call does not specify a prefix, the writer uses the last prefix pushed onto the namespace stack, and produces the following XML:

          <x:root xmlns:x="urn:1">
           <y:item y:attr="123" xmlns:y="urn:1" />
          </x:root>
        

If namespace conflicts occur, XmlTextWriter resolves them by generating alternate prefixes. For example, if an attribute and element have the same prefix but different namespaces, XmlWriter generates an alternate prefix for the attribute. The generated prefixes are named n{i} where i is a number beginning at 1. The number is reset to 1 for each element.

Attributes which are associated with a namespace URI must have a prefix (default namespaces do not apply to attributes). This conforms to section 5.2 of the W3C Namespaces in XML recommendation. If an attribute references a namespace URI, but does not specify a prefix, the writer generates a prefix for the attribute.

When writing an empty element, an additional space is added between tag name and the closing tag, for example <item />. This provides compatibility with older browsers.

When a String is used as method parameter, null and String.Empty are equivalent.String.Empty follows the W3C rules.

To write strongly typed data, use the XmlConvert class to convert data types to string. For example, the following C# code converts the data from Double to String and writes the element <price>19.95</price> .

          Double price = 19.95;
          writer.WriteElementString("price", XmlConvert.ToString(price));
        
For more information on writing XML, see the conceptual topic at MSDN: writingxmlwithxmlwriter.
See also:
System.Xml Namespace

System.Xml.XmlTextWriter Member List:

Public Constructors
ctor #1 Overloaded:
.ctor(TextWriter w)

Creates an instance of the XmlTextWriter class using the specified TextWriter.
ctor #2 Overloaded:
.ctor(Stream w, Encoding encoding)

Creates an instance of the XmlTextWriter class using the specified stream.
ctor #3 Overloaded:
.ctor(string filename, Encoding encoding)

Creates an instance of the XmlTextWriter class using the specified file.
Public Properties
BaseStream Read-only

Gets the underlying stream object.
Formatting Read-write

Indicates how the output is formatted.
Indentation Read-write

Gets or sets how many IndentChars to write for each level in the hierarchy when XmlTextWriter.Formatting is set to Formatting.Indented.
IndentChar Read-write

Gets or sets which character to use for indenting when XmlTextWriter.Formatting is set to Formatting.Indented.
Namespaces Read-write

Gets or sets a value indicating whether to do namespace support.
QuoteChar Read-write

Gets or sets which character to use to quote attribute values.
WriteState Read-only

Overridden:
Gets the state of the writer.
XmlLang Read-only

Overridden:
Gets the current xml:lang scope.
XmlSpace Read-only

Overridden:
Gets an XmlSpace representing the current xml:space scope.
Public Methods
Close Overridden:
Closes this stream and the underlying stream.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
Flush Overridden:
Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
LookupPrefix Overridden:
Returns the closest prefix defined in the current namespace scope for the namespace URI.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
WriteAttributes
(inherited from System.Xml.XmlWriter)
See base class member description: System.Xml.XmlWriter.WriteAttributes


When overridden in a derived class, writes out all the attributes found at the current position in the XmlReader.
WriteAttributeString
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteAttributeString(string localName, string value)

See base class member description: System.Xml.XmlWriter.WriteAttributeString


When overridden in a derived class, writes out the attribute with the specified local name and value.
WriteAttributeString
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteAttributeString(string localName, string ns, string value)

See base class member description: System.Xml.XmlWriter.WriteAttributeString


When overridden in a derived class, writes an attribute with the specified parameters.
WriteAttributeString
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteAttributeString(string prefix, string localName, string ns, string value)

See base class member description: System.Xml.XmlWriter.WriteAttributeString


When overridden in a derived class, writes out the attribute with the specified prefix, local name, namespace URI and value.
WriteBase64 Overridden:
Encodes the specified binary bytes as base64 and writes out the resulting text.
WriteBinHex Overridden:
Encodes the specified binary bytes as binhex and writes out the resulting text.
WriteCData Overridden:
Writes out a <![CDATA[...]]> block containing the specified text.
WriteCharEntity Overridden:
Forces the generation of a character entity for the specified Unicode character value.
WriteChars Overridden:
Writes text a buffer at a time.
WriteComment Overridden:
Writes out a comment <!--...--> containing the specified text.
WriteDocType Overridden:
Writes the DOCTYPE declaration with the specified name and optional attributes.
WriteElementString
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteElementString(string localName, string value)

See base class member description: System.Xml.XmlWriter.WriteElementString


When overridden in a derived class, writes an element with the specified local name and value.
WriteElementString
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteElementString(string localName, string ns, string value)

See base class member description: System.Xml.XmlWriter.WriteElementString


When overridden in a derived class, writes an element with the specified parameters.
WriteEndAttribute Overridden:
Closes the previous XmlTextWriter.WriteStartAttribute call.
WriteEndDocument Overridden:
Closes any open elements or attributes and puts the writer back in the Start state.
WriteEndElement Overridden:
Closes one element and pops the corresponding namespace scope.
WriteEntityRef Overridden:
Writes out an entity reference as follows: & name;.
WriteFullEndElement Overridden:
Closes one element and pops the corresponding namespace scope.
WriteName Overridden:
Writes out the specified name, ensuring it is a valid name according to the W3C XML 1.0 recommendation(http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name ).
WriteNmToken Overridden:
Writes out the specified name, ensuring it is a valid NmToken according to the W3C XML 1.0 recommendation(http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
WriteNode
(inherited from System.Xml.XmlWriter)
See base class member description: System.Xml.XmlWriter.WriteNode


When overridden in a derived class, copies everything from the reader to the writer and moves the reader to the start of the next sibling.
WriteProcessingInstruction Overridden:
Writes out a processing instruction with a space between the name and text as follows: <?name text?>.
WriteQualifiedName Overridden:
Writes out the namespace-qualified name. This method looks up the prefix that is in scope for the given namespace.
WriteRaw Overloaded:
WriteRaw(string data)

Overridden:
Writes raw markup manually from a string.
WriteRaw Overloaded:
WriteRaw(char[] buffer, int index, int count)

Overridden:
Writes raw markup manually from a character buffer.
WriteStartAttribute
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteStartAttribute(string localName, string ns)

See base class member description: System.Xml.XmlWriter.WriteStartAttribute


When overridden in a derived class, writes the start of an attribute.
WriteStartAttribute Overloaded:
WriteStartAttribute(string prefix, string localName, string ns)

Overridden:
Writes the start of an attribute.
WriteStartDocument Overloaded:
WriteStartDocument()

Overridden:
Writes the XML declaration with the version "1.0".
WriteStartDocument Overloaded:
WriteStartDocument(bool standalone)

Overridden:
Writes the XML declaration with the version "1.0" and the standalone attribute.
WriteStartElement
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteStartElement(string localName)

See base class member description: System.Xml.XmlWriter.WriteStartElement


When overridden in a derived class, writes out a start tag with the specified local name.
WriteStartElement
(inherited from System.Xml.XmlWriter)
Overloaded:
WriteStartElement(string localName, string ns)

See base class member description: System.Xml.XmlWriter.WriteStartElement


When overridden in a derived class, writes the specified start tag and associates it with the given namespace.
WriteStartElement Overloaded:
WriteStartElement(string prefix, string localName, string ns)

Overridden:
Writes the specified start tag and associates it with the given namespace and prefix.
WriteString Overridden:
Writes the given text content.
WriteSurrogateCharEntity Overridden:
Generates and writes the surrogate character entity for the surrogate character pair.
WriteWhitespace Overridden:
Writes out the given white space.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Xml.XmlTextWriter Member Details

Overloaded ctor #1
Summary
Creates an instance of the XmlTextWriter class using the specified TextWriter.
C# Syntax:
public XmlTextWriter(
   TextWriter w
);
Parameters:

w

The TextWriter to write to. It is assumed that the TextWriter is already set to the correct encoding.

Return to top


Overloaded ctor #2
Summary
Creates an instance of the XmlTextWriter class using the specified stream.
C# Syntax:
public XmlTextWriter(
   Stream w,
   Encoding encoding
);
Parameters:

w

The stream to which you want to write.

encoding

The encoding to generate. If encoding is null it writes out the stream as UTF-8 and omits the encoding attribute from the ProcessingInstruction.

Exceptions
Exception Type Condition
ArgumentException The encoding is not supported or the stream cannot be written to.

Return to top


Overloaded ctor #3
Summary
Creates an instance of the XmlTextWriter class using the specified file.
C# Syntax:
public XmlTextWriter(
   string filename,
   Encoding encoding
);
Parameters:

filename

The filename to write to. If the file exists, it will truncate it and overwrite it with the new content.

encoding

The encoding to generate. If encoding is null it writes the file out as UTF-8, and omits the encoding attribute from the ProcessingInstruction.

Exceptions
Exception Type Condition
ArgumentException The encoding is not supported; the filename is empty, contains only white space, or contains one or more invalid characters.
UnauthorizedAccessException Access is denied.
ArgumentNullException The filename is null.
DirectoryNotFoundException The directory to write to is not found.
IOException The filename includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.
SecurityException The caller does not have the required permission.

Return to top


Property: BaseStream (read-only)
Summary
Gets the underlying stream object.
C# Syntax:
public Stream BaseStream {get;}
Remarks
If the writer was constructed using a TextWriter that is a subclass of the StreamWriter class, this property is equivalent to the StreamWriter.BaseStream property. If the writer was constructed using a Stream, this property returns the Stream passed to the constructor. If the writer was constructed using a file name, this property returns the Stream representing the file.

Return to top


Property: Formatting (read-write)
Summary
Indicates how the output is formatted.
C# Syntax:
public Formatting Formatting {get; set;}
Remarks
If the Indented option is set, child elements are indented using the XmlTextWriter.Indentation and XmlTextWriter.IndentChar properties. Only element content will be indented. The following C# code writes out HTML elements including mixed content:
              XmlTextWriter w = new XmlTextWriter(Console.Out); 
               w.Formatting = Formatting.Indented; 
               w.WriteStartElement("ol"); 
               w.WriteStartElement("li"); 
               w.WriteString("The big "); // This means "li" now has a mixed content model. 
               w.WriteElementString("b", "E"); 
               w.WriteElementString("i", "lephant"); 
               w.WriteString(" walks slowly."); 
               w.WriteEndElement(); 
               w.WriteEndElement();
                 
            

The above code produces the following output:

              <ol> 
                <li>The big <b>E</b><i>lephant</i> walks slowly.</li> 
              </ol>
                 
            

When this is viewed in HTML no white space appears between the bold and italic elements. In fact, in this example, if indenting was added between these elements the word "Elephant" would be incorrectly broken.



Note Writing any text content, including String.Empty puts that element into mixed content mode. Child elements do not inherit this "mixed" mode status. A child element of a "mixed" element will do indenting, unless it is also contains "mixed" content. Element content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-element-content) and mixed content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-mixed-content) are defined according to the XML 1.0 definitions of these terms.
Example
The following example writes an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer.
     writer.Close();  

  }

}

    
See also:
Formatting

Return to top


Property: Indentation (read-write)
Summary
Gets or sets how many IndentChars to write for each level in the hierarchy when XmlTextWriter.Formatting is set to Formatting.Indented.
C# Syntax:
public int Indentation {get; set;}
Exceptions
Exception Type Condition
ArgumentException Setting this property to a negative value.
Remarks
Indentation is performed on following node types: DocumentType, Element, Comment, ProcessingInstruction, and CDATASection. All other node types are not affected. The XmlTextWriter does not indent the internal DTD subset. However, you could do the following to apply formatting to the internal DTD subset.
              String name = "Employees";
              String pubid = null;
              String sysid = null;
              String subset =
              @"
                  <!ELEMENT Employees (Employee)+>
                  <!ELEMENT Employee EMPTY>
                  <!ATTLIST Employee firstname CDATA #REQUIRED>
                  <!ENTITY Company 'Microsoft'>]>
              ";
              XmlTextWriter tw = new XmlTextWriter(Console.Out);
              tw.WriteDocType(name, pubid, sysid, subset);
                 
            
Example
The following example writes an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer.
     writer.Close();  

  }

}

    
See also:
XmlTextWriter.IndentChar | Formatting

Return to top


Property: IndentChar (read-write)
Summary
Gets or sets which character to use for indenting when XmlTextWriter.Formatting is set to Formatting.Indented.
C# Syntax:
public char IndentChar {get; set;}
See also:
XmlTextWriter.Indentation | Formatting

Return to top


Property: Namespaces (read-write)
Summary
Gets or sets a value indicating whether to do namespace support.
C# Syntax:
public bool Namespaces {get; set;}
Exceptions
Exception Type Condition
InvalidOperationException You can only change this property when in the WriteState.Start state.
Remarks
This property determines whether the writer supports the W3C Namespaces in XML recommendation located at www.w3.org/TR/REC-xml-names .

Return to top


Property: QuoteChar (read-write)
Summary
Gets or sets which character to use to quote attribute values.
C# Syntax:
public char QuoteChar {get; set;}
Exceptions
Exception Type Condition
ArgumentException Setting this property to something other than either a single or double quote.

Return to top


Overridden Property: WriteState (read-only)
Summary
Gets the state of the writer.
C# Syntax:
public override WriteState WriteState {get;}

Return to top


Overridden Property: XmlLang (read-only)
Summary
Gets the current xml:lang scope.
C# Syntax:
public override string XmlLang {get;}
Remarks
This property allows one component to find out what state another component has left the writer in. For example, perhaps one component wants to tell another which language help text to generate. The language information is communicated by writing an xml:lang attribute.

Return to top


Overridden Property: XmlSpace (read-only)
Summary
Gets an XmlSpace representing the current xml:space scope.
C# Syntax:
public override XmlSpace XmlSpace {get;}
Remarks
This allows one component to find out in what state another component has left the writer.
Example
The following example uses the WriteWhitespace method to control how the file is formatted.
using System;
using System.IO;
using System.Xml;

public class Sample
{  
  public static void Main()
  {
    // Create the writer.
    XmlTextWriter writer = null;
    writer = new XmlTextWriter ("ws.html", null);

    // Write an element (this one is the root).
    writer.WriteStartElement("p");

    // Write the xml:space attribute.
    writer.WriteAttributeString("xml", "space", null, "preserve");

    // Verify that xml:space is set properly.
    if (writer.XmlSpace == XmlSpace.Preserve)
      Console.WriteLine("xmlspace is correct!");

    // Write out the HTML elements.  Insert white space
    // between 'something' and 'Big'
    writer.WriteString("something");
    writer.WriteWhitespace("  ");
    writer.WriteElementString("b", "B");
    writer.WriteString("ig");

    // Write the root end element.
    writer.WriteEndElement();
             
    // Write the XML to file and close the writer.
    writer.Close();  
  }
}

    

Return to top


Overridden Method: Close()
Summary
Closes this stream and the underlying stream.
C# Syntax:
public override void Close();
Exceptions
Exception Type Condition
InvalidOperationException A call is made to write more output after Close has been called or the result of this call is an invalid XML document.
Remarks
Any elements or attributes left open will be automatically closed.
Example
The following example writes an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer.
     writer.Close();  

  }

}

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XmlTextWriter();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: Flush()
Summary
Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
C# Syntax:
public override void Flush();
Remarks
This is called instead of XmlTextWriter.Close when you want to write more to the underlying stream without losing what is still in the buffer.
Example
The following example writes out two XML fragments.
using System;
using System.IO;
using System.Xml;

public class Sample
{

  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter (Console.Out);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
	
     //Write an XML fragment.
     writer.WriteStartElement("book");
     writer.WriteElementString("title", "Pride And Prejudice");
     writer.WriteEndElement();
     writer.Flush();

     //Write another XML fragment.
     writer.WriteStartElement("cd");
     writer.WriteElementString("title", "Americana");
     writer.WriteEndElement();
     writer.Flush();  

     //Close the writer.
     writer.Close();
  }
}

    

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Overridden Method: LookupPrefix(
   string ns
)
Summary
Returns the closest prefix defined in the current namespace scope for the namespace URI.
C# Syntax:
public override string LookupPrefix(
   string ns
);
Parameters:

ns

Namespace URI whose prefix you want to find.

Return Value:
The matching prefix. Or null if no matching namespace URI is found in the current scope.
Exceptions
Exception Type Condition
ArgumentException ns is either null or String.Empty.
Example
The following example writes out a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {

     XmlTextWriter writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     writer.WriteComment("sample XML fragment");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("bookstore");

     //Write the namespace declaration
     writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

     writer.WriteStartElement("book");

     //Lookup the prefix and then write the ISBN attribute
     string prefix = writer.LookupPrefix("urn:samples");
     writer.WriteStartAttribute(prefix, "ISBN", "urn:samples");
     writer.WriteString("1-861003-78");
     writer.WriteEndAttribute();     

     //Write the title
     writer.WriteStartElement("title");
     writer.WriteString("The Handmaid's Tale");
     writer.WriteEndElement();
              
     //Write the price
     writer.WriteElementString("price", "19.95");
     
     //Write the style element
     writer.WriteStartElement(prefix, "style", "urn:samples");
     writer.WriteString("hardcover");
     writer.WriteEndElement();

     //Write the end tag for the book element
     writer.WriteEndElement();

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();

     //Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: WriteAttributes(
   XmlReader reader,
   bool defattr
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteAttributes

Summary
When overridden in a derived class, writes out all the attributes found at the current position in the XmlReader.
C# Syntax:
public virtual void WriteAttributes(
   XmlReader reader,
   bool defattr
);
Parameters:

reader

The XmlReader from which to copy the attributes.

defattr

true to copy the default attributes from the XmlReader; otherwise, false.

Exceptions
Exception Type Condition
ArgumentException reader is null.
XmlException The reader is not positioned on either an element, attribute or XmlDeclaration node.
Remarks
If the reader is positioned on an element node WriteAttributes copies all the contained attributes. If the reader is positioned on an attribute node, this method writes the current attribute, then the rest of the attributes until the element closing tag. If the reader is positioned on an XmlDeclaration node, this method writes all the attributes in the declaration. If the reader is positioned on any other node type this method has no operation.

If this method is called using XmlValidatingReader, to ensure well-formed XML any content (which has been expanded from the entities) that could result in an invalid document is replaced when written. For example, if an attribute includes an &gt; entity that has been expanded, to ensure a well-formed document the expanded ">" is replaced when written out with &gt;.

Example
The following example copies all the elements to the output, changes the tag names to upper case, and copies all the attributes unchanged.
using System;
using System.IO;
using System.Xml;

public class Sample
{

  public static void Main()
  {
    XmlTextReader reader = new XmlTextReader("test1.xml");
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting = Formatting.Indented;

    while (reader.Read())
    {
      if (reader.NodeType == XmlNodeType.Element)
      {
        writer.WriteStartElement(reader.Name.ToUpper());
        writer.WriteAttributes(reader, false);
        if (reader.IsEmptyElement) writer.WriteEndElement();
      }
      else if (reader.NodeType == XmlNodeType.EndElement)
      {
        writer.WriteEndElement();
      }
    }
    writer.Close();
    reader.Close();
  }
}

    
The example uses the file, test1.xml, as input.

<test a="1" b="2">
  <item c="3" d="4" e="5" f="6"/>
</test>

    
See also:
EntityHandling

Return to top


Overloaded Method: WriteAttributeString(
   string localName,
   string value
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteAttributeString

Summary
When overridden in a derived class, writes out the attribute with the specified local name and value.
C# Syntax:
public void WriteAttributeString(
   string localName,
   string value
);
Parameters:

localName

The local name of the attribute.

value

The value of the attribute.

Exceptions
Exception Type Condition
InvalidOperationException The state of writer is not WriteState.Element or writer is closed.
ArgumentException The xml:space or xml:lang attribute value is invalid.
Remarks
WriteAttributeString does the following
Example
See XmlTextWriter.WriteEndAttribute (in the XmlTextWriter class) for an example using this method.

Return to top


Overloaded Method: WriteAttributeString(
   string localName,
   string ns,
   string value
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteAttributeString

Summary
When overridden in a derived class, writes an attribute with the specified parameters.
C# Syntax:
public void WriteAttributeString(
   string localName,
   string ns,
   string value
);
Parameters:

localName

The local name of the attribute.

ns

The namespace URI to associate with the attribute.

value

The value of the attribute.

Exceptions
Exception Type Condition
InvalidOperationException The state of writer is not WriteState.Element or writer is closed.
ArgumentException The xml:space or xml:lang attribute value is invalid.
Remarks
This method writes out the attribute with a user defined namespace prefix and associates it with the given namespace. If localName is "xmlns" then this method also treats this as a namespace declaration. In this case, the ns argument can be null.

WriteAttributeString does the following

Example
The following example writes out a portion of a XSD schema.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     //Write an element (this one is the root)
     writer.WriteStartElement("schema");

     //Write the namespace declarations.
     writer.WriteAttributeString("xmlns", null,"http://www.w3.org/2001/XMLSchema");
     writer.WriteAttributeString("xmlns","po",null,"http://contoso.com/po");

     writer.WriteStartElement("element");

     writer.WriteAttributeString("name", "purchaseOrder");

     //Write the type attribute
     writer.WriteStartAttribute(null,"type", null);
     writer.WriteQualifiedName("PurchaseOrder", "http://contoso.com/po");
     writer.WriteEndAttribute();

     writer.WriteEndElement();


     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     // Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);

  }

}

    

Return to top


Overloaded Method: WriteAttributeString(
   string prefix,
   string localName,
   string ns,
   string value
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteAttributeString

Summary
When overridden in a derived class, writes out the attribute with the specified prefix, local name, namespace URI and value.
C# Syntax:
public void WriteAttributeString(
   string prefix,
   string localName,
   string ns,
   string value
);
Parameters:

prefix

The namespace prefix of the attribute.

localName

The local name of the attribute.

ns

The namespace URI of the attribute.

value

The value of the attribute.

Exceptions
Exception Type Condition
InvalidOperationException The state of writer is not WriteState.Element or writer is closed.
ArgumentException The xml:space or xml:lang attribute value is invalid.
Remarks
This method writes out the attribute with a user defined namespace prefix and associates it with the given namespace. If the prefix is "xmlns" then this method also treats this as a namespace declaration and associates the declared prefix with the namespace URI provided in the given attribute value. In this case the ns argument can be null.

WriteAttributeString does the following

Example
The following example writes out a portion of a XSD schema.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     //Write an element (this one is the root)
     writer.WriteStartElement("schema");

     //Write the namespace declarations.
     writer.WriteAttributeString("xmlns", null,"http://www.w3.org/2001/XMLSchema");
     writer.WriteAttributeString("xmlns","po",null,"http://contoso.com/po");

     writer.WriteStartElement("element");

     writer.WriteAttributeString("name", "purchaseOrder");

     //Write the type attribute
     writer.WriteStartAttribute(null,"type", null);
     writer.WriteQualifiedName("PurchaseOrder", "http://contoso.com/po");
     writer.WriteEndAttribute();

     writer.WriteEndElement();


     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     // Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);

  }

}

    

Return to top


Overridden Method: WriteBase64(
   byte[] buffer,
   int index,
   int count
)
Summary
Encodes the specified binary bytes as base64 and writes out the resulting text.
C# Syntax:
public override void WriteBase64(
   byte[] buffer,
   int index,
   int count
);
Parameters:

buffer

Byte array to encode.

index

The position within the buffer indicating the start of the bytes to write.

count

The number of bytes to write.

Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException The buffer length minus index is less than count.
ArgumentOutOfRangeException index or count is less than zero.
Remarks
For example, the byte buffer may contain the binary contents of a GIF image. This clearly would not be valid XML. The Base64 encoding is designed to represent arbitrary byte sequences in a text form comprised of the 65 US-ASCII characters ([A-Za-z0-9+/=]) where each character encodes 6 bits of the binary data. See RFC 1521. (You can obtain RFCs from the Request for Comments Web site at http://www.rfc-editor.org/.)
Example
The following example encodes an input file using WriteBase64 and generates a temporary XML file. The temporary XML file is decoded using the XmlTextReader.ReadBase64 method and compared to the original file.
using System;
using System.IO;
using System.Xml;
using System.Text;

class TestBase64 {

    private const int bufferSize=4096;

    public static void Main(String[] args) {

        TestBase64 testBase64=new TestBase64();

        //Check that the usage string is correct.
        if (args.Length < 2 ) {
            testBase64.Usage();
            return;
        }

        FileStream fileOld = new FileStream(args[0], FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
        testBase64.EncodeXmlFile("temp.xml", fileOld);

        FileStream fileNew = new FileStream(args[1], FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

        testBase64.DecodeOrignalObject("temp.xml", fileNew);

        //Compare the two files.
        if (testBase64.CompareResult( fileOld, fileNew)) {
            Console.WriteLine("The recreated binary file {0} is the same as {1}", args[1], args[0] );
        } else {
            Console.WriteLine("The recreated binary file {0} is not the same as {1}", args[1], args[0] );
        }

        fileOld.Flush();
        fileNew.Flush();
        fileOld.Close();
        fileNew.Close();

    }

    //Use the WriteBase64 method to create an XML document.  The object  
    //passed by the user is encoded and included in the document.
    public void EncodeXmlFile(String xmlFileName, FileStream fileOld) {

        byte[] buffer = new byte[bufferSize];
        int readByte=0;

        XmlTextWriter xw = new XmlTextWriter(xmlFileName, Encoding.UTF8);
        xw.WriteStartDocument();
        xw.WriteStartElement("root");
        // Create a Char writer.
        BinaryReader br = new BinaryReader(fileOld);
        // Set the file pointer to the end.

        try {
              do {
                  readByte=br.Read(buffer, 0, bufferSize);
                  xw.WriteBase64(buffer, 0, readByte);
              } while (bufferSize <= readByte );

        } catch (Exception ex) {
            EndOfStreamException ex1= new EndOfStreamException();

            if (ex1.Equals(ex)) {
                Console.WriteLine("We are at end of file");
            } else {
                Console.WriteLine(ex);
            }
        }
        xw.WriteEndElement();
        xw.WriteEndDocument();

        xw.Flush();
        xw.Close();
    }

    //Use the ReadBase64 method to decode the new XML document 
    //and generate the original object.
    public void DecodeOrignalObject(String xmlFileName, FileStream fileNew) {

        byte[] buffer = new byte[bufferSize];
        int readByte=0;

        //Create a file to write the bmp back.
        BinaryWriter bw = new BinaryWriter(fileNew);

        XmlTextReader tr = new XmlTextReader(xmlFileName);
        tr.MoveToContent();
        Console.WriteLine(tr.Name);

        do {
          readByte=tr.ReadBase64(buffer, 0, bufferSize);
          bw.Write(buffer, 0, readByte);
        } while(readByte>=bufferSize);

        bw.Flush();

    }

    //Compare the two files.
    public bool CompareResult(FileStream fileOld, FileStream fileNew) {

        int readByteOld=0;
        int readByteNew=0;
        int count, readByte=0;

        byte[] bufferOld = new byte[bufferSize];
        byte[] bufferNew = new byte[bufferSize];


        BinaryReader binaryReaderOld = new BinaryReader(fileOld);
        BinaryReader binaryReaderNew = new BinaryReader(fileNew);

        binaryReaderOld.BaseStream.Seek(0, SeekOrigin.Begin);
        binaryReaderNew.BaseStream.Seek(0, SeekOrigin.Begin);


        do {
          readByteOld=binaryReaderOld.Read(bufferOld, 0, bufferSize);
          readByteNew=binaryReaderNew.Read(bufferNew, 0, bufferSize);

          if (readByteOld!=readByteNew) {
              return false;
          }

          for (count=0; count <bufferSize; ++count) {
              if (bufferOld[count]!=bufferNew[count]) {
                  return false;
              }
          }

        } while (count<readByte );

        return true;

    }

    //Display the usage statement.
    public void Usage() {
        Console.WriteLine("TestBase64 sourceFile, targetFile \n");
        Console.WriteLine("For example: TestBase64 winlogon.bmp, target.bmp\n");
    }

}

    

Return to top


Overridden Method: WriteBinHex(
   byte[] buffer,
   int index,
   int count
)
Summary
Encodes the specified binary bytes as binhex and writes out the resulting text.
C# Syntax:
public override void WriteBinHex(
   byte[] buffer,
   int index,
   int count
);
Parameters:

buffer

Byte array to encode.

index

The position within the buffer indicating the start of the bytes to write.

count

The number of bytes to write.

Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException The buffer length minus index is less than count.
ArgumentOutOfRangeException index or count is less than zero.

Return to top


Overridden Method: WriteCData(
   string text
)
Summary
Writes out a <![CDATA[...]]> block containing the specified text.
C# Syntax:
public override void WriteCData(
   string text
);
Parameters:

text

Text to place inside the CDATA block.

Exceptions
Exception Type Condition
ArgumentException The text would result in a non-well formed XML document.
Remarks
If text is either null or String.Empty, this method writes an empty CData block, for example <![CDATA[]]>.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteCharEntity(
   char ch
)
Summary
Forces the generation of a character entity for the specified Unicode character value.
C# Syntax:
public override void WriteCharEntity(
   char ch
);
Parameters:

ch

Unicode character for which to generate a character entity.

Exceptions
Exception Type Condition
ArgumentException The character is in the surrogate pair character range, 0xd800 - 0xdfff; or the text would result in a non-well formed XML document.
Remarks
This method writes the Unicode character in hexidecimal character entity reference format.
Example
The following example writes out elements with various data types.
using System;
using System.IO;
using System.Xml;
public class SampleWriteXml 
{
   private const string m_Document = "sampledata.xml";
 
   public static void Main()
   {
      XmlTextWriter writer = null;
      XmlTextReader reader = null;
 
      try
      {
        writer = new XmlTextWriter (m_Document, null);
        //Use indenting for readability
        writer.Formatting = Formatting.Indented;
        writer.Indentation=4;
 
        //Start the document with the XML declaration tag
        writer.WriteStartDocument();
 
        //Write a comment
        writer.WriteComment("Sample XML file");
 
        //Write an element (this is the root)
        writer.WriteStartElement("TestElements","");
     
        //write a char entity
        writer.WriteStartElement("Item");
        writer.WriteString("Write out char entity:  ");
        writer.WriteCharEntity('&');
        writer.WriteEndElement();
 
        //Write out raw markup.  Note:  Depending on the string, this could
        //result in XML that is not well-formed
        writer.WriteStartElement("Item");
        writer.WriteString("Write out raw:  ");
        writer.WriteRaw("<test/>");
        writer.WriteEndElement();
 
        //Write out Boolean value.
        writer.WriteStartElement("Item");
        writer.WriteString("Write out Boolean:  ");
        writer.WriteString(XmlConvert.ToString(false));
        writer.WriteEndElement();
 
        //Write out Date.
        writer.WriteStartElement("Item");
        writer.WriteString("Write out Date:  ");
        DateTime vDate = new DateTime(2000, 01, 01 );
        writer.WriteString(XmlConvert.ToString(vDate));
        writer.WriteEndElement();
 
        //Write out DateTime.
        writer.WriteStartElement("Item");
        writer.WriteString("Write out DateTime:  ");
        DateTime vDateTime = new DateTime(2000, 01, 01 ,12, 0, 30, 500);
        writer.WriteString(XmlConvert.ToString(vDateTime));
        writer.WriteEndElement();
 
        //Write out Time.
        writer.WriteStartElement("Item");
        writer.WriteString("Write out Time:  ");
        DateTime vTime = new DateTime(1, 1, 1 ,12, 0, 30, 500);
        writer.WriteString(XmlConvert.ToString(vTime));
        writer.WriteEndElement();
 
        //Write out TimeSpan.
        writer.WriteStartElement("Item");
        writer.WriteString("Write out TimeSpan:  ");
        TimeSpan vTimeSpan = new TimeSpan(1, 15 ,32);
        writer.WriteString(XmlConvert.ToString(vTimeSpan));
        writer.WriteEndElement();
 
        //Write out Single value.
        writer.WriteStartElement("Item");
        writer.WriteString("Write out Single:  ");
        Single vSingle = ((Single)22)/((Single)7);
        writer.WriteString(XmlConvert.ToString(vSingle));
        writer.WriteEndElement();
 
        //Write the close tag for the root element.
        writer.WriteEndElement();
              
        writer.WriteEndDocument();
     
        //Write the XML to file and close the writer.
        writer.Flush();
        writer.Close();  
 
        //Read the file back in and parse to ensure well formed XML.
        reader = new XmlTextReader (m_Document);
        XmlDocument doc = new XmlDocument();
        //Preserve whitespace for readability
        doc.PreserveWhitespace = true;
        //Load the file
        doc.Load(reader);
     
        //Write the XML content to the console.
        Console.WriteLine(doc.InnerXml);
      }
      catch (Exception e)
      {
        Console.WriteLine ("Exception: {0}", e.ToString());
      }        
 
      finally 
      {
        Console.WriteLine();
        Console.WriteLine("Processing of the file {0} complete.", m_Document);
        if (reader != null)
           reader.Close();
        //Close the writer
        if (writer != null)
           writer.Close();
     } 
   }
 
}

    

Return to top


Overridden Method: WriteChars(
   char[] buffer,
   int index,
   int count
)
Summary
Writes text a buffer at a time.
C# Syntax:
public override void WriteChars(
   char[] buffer,
   int index,
   int count
);
Parameters:

buffer

Character array containing the text to write.

index

The position within the buffer indicating the start of the text to write.

count

The number of characters to write.

Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException The buffer length minus index is less than count; the call results in surrogate pair characters being split or an invalid surrogate pair being written.
ArgumentOutOfRangeException index or count is less than zero.
Remarks
This method can be used to write large amounts of text a buffer at a time.

Special handling must be done to ensure the WriteChars method does not split surrogate pair characters across multiple buffer writes. The XML specification defines the valid ranges for surrogate pairs.

An exception is thrown if surrorgate pair characters are written that would result in the surrogate pair characters being split in the buffer. This exception must be caught in order to continue writing the next surrogate pair character to the output buffer.

In the following example a randomly generated surrogate pair character is split when writing to the output buffer. Catching the exception and continuing to write to the buffer ensures that the surrogate pair character is written correctly to the output stream.

              //Handling surrogate pair across buffer streams.
              char [] charArray = new char[4];
              char lowChar, highChar;
              Random random = new Random();
              lowChar = Convert.ToChar(random.Next(0xDC01, 0xDFFF));
              highChar = Convert.ToChar(random.Next(0xD801, 0xDBFF));
              XmlTextWriter tw = new XmlTextWriter("test.xml", null);
              tw.WriteStartElement("Root");
              charArray[0] = 'a';
              charArray[1] = 'b';
              charArray[2] = 'c';
              charArray[3] = highChar;
              try
              {
               tw. WriteChars(charArray, 0, charArray.Length);
              }
              catch (Exception ex) {
              }
              Array[0] = highChar;
              Array[1] = lowChar;
              charArray[2] = 'd';
              tw.WriteChars(charArray, 0, 3); 
              tw.WriteEndElement();
            

Return to top


Overridden Method: WriteComment(
   string text
)
Summary
Writes out a comment <!--...--> containing the specified text.
C# Syntax:
public override void WriteComment(
   string text
);
Parameters:

text

Text to place inside the comment.

Exceptions
Exception Type Condition
ArgumentException The text would result in a non-well formed XML document
Remarks
If text is either null or String.Empty, this method writes a Comment with no data content, for example <!---->.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteDocType(
   string name,
   string pubid,
   string sysid,
   string subset
)
Summary
Writes the DOCTYPE declaration with the specified name and optional attributes.
C# Syntax:
public override void WriteDocType(
   string name,
   string pubid,
   string sysid,
   string subset
);
Parameters:

name

The name of the DOCTYPE. This must be non-empty.

pubid

If non-null it also writes PUBLIC "pubid" "sysid" where pubid and sysid are replaced with the value of the given arguments.

sysid

If pubid is null and sysid is non-null it writes SYSTEM "sysid" where sysid is replaced with the value of this argument.

subset

If non-null it writes [subset] where subset is replaced with the value of this argument.

Exceptions
Exception Type Condition
InvalidOperationException This method was called outside the prolog (after the root element).
ArgumentException The value for name would result in invalid XML.
Remarks
This method does not check for invalid characters in pubid, sysid or subset.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overloaded Method: WriteElementString(
   string localName,
   string value
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteElementString

Summary
When overridden in a derived class, writes an element with the specified local name and value.
C# Syntax:
public void WriteElementString(
   string localName,
   string value
);
Parameters:

localName

The local name of the element

value

The value of the element

Exceptions
Exception Type Condition
InvalidOperationException This results in an invalid XML document.
ArgumentException localName is either null or String.Empty.
Example
The following example uses several write methods to create an XML fragment.
using System;
using System.IO;
using System.Xml;
 
 public class Sample
 {
   private const string m_Document = "sampledata.xml";
 
   public static void Main()
   {
      XmlTextWriter writer = null;
      XmlTextReader reader = null;
 
      try
      {
        writer = new XmlTextWriter (m_Document, null);
        // Use indenting for readability.
        writer.Formatting = Formatting.Indented;
        writer.Indentation=4;
         
        writer.WriteComment("sample XML fragment");
     
        // Write an element (this one is the root).
        writer.WriteStartElement("book");
 
        // Write the namespace declaration.
        writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");
    
        // Write the genre attribute.
        writer.WriteAttributeString("genre", "novel");
         
        // Write the title.
        writer.WriteStartElement("title");
        writer.WriteString("The Handmaid's Tale");
        writer.WriteEndElement();
               
        // 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");
        writer.WriteString("1-861003-78");
        writer.WriteEndElement();

        // 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.
        writer.WriteEndElement();
              
 
        // Write the XML to file and close the writer.
        writer.Flush();
        writer.Close();
 
 
        // Read the file back in and parse to ensure well formed XML.
        reader = new XmlTextReader (m_Document);
        XmlDocument doc = new XmlDocument();
        // Preserve white space for readability.
        doc.PreserveWhitespace = true;
        //Load the file
        doc.Load(reader);
     
        // Write the XML content to the console.
        Console.Write(doc.InnerXml);
      }

      finally 
      {
        Console.WriteLine();
        Console.WriteLine("Processing of the file {0} complete.", m_Document);
        if (reader != null)
           reader.Close();
        if (writer != null)
           writer.Close();
     } 
   }
 
 }

    

Return to top


Overloaded Method: WriteElementString(
   string localName,
   string ns,
   string value
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteElementString

Summary
When overridden in a derived class, writes an element with the specified parameters.
C# Syntax:
public void WriteElementString(
   string localName,
   string ns,
   string value
);
Parameters:

localName

The local name of the element

ns

The namespace URI to associate with the element

value

The value of the element

Exceptions
Exception Type Condition
InvalidOperationException This results in an invalid XML document.
ArgumentException localName is either null or String.Empty.
Example
The following example uses several write methods to create an XML fragment.
using System;
using System.IO;
using System.Xml;
 
 public class Sample
 {
   private const string m_Document = "sampledata.xml";
 
   public static void Main()
   {
      XmlTextWriter writer = null;
      XmlTextReader reader = null;
 
      try
      {
        writer = new XmlTextWriter (m_Document, null);
        // Use indenting for readability.
        writer.Formatting = Formatting.Indented;
        writer.Indentation=4;
         
        writer.WriteComment("sample XML fragment");
     
        // Write an element (this one is the root).
        writer.WriteStartElement("book");
 
        // Write the namespace declaration.
        writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");
    
        // Write the genre attribute.
        writer.WriteAttributeString("genre", "novel");
         
        // Write the title.
        writer.WriteStartElement("title");
        writer.WriteString("The Handmaid's Tale");
        writer.WriteEndElement();
               
        // 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");
        writer.WriteString("1-861003-78");
        writer.WriteEndElement();

        // 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.
        writer.WriteEndElement();
              
 
        // Write the XML to file and close the writer.
        writer.Flush();
        writer.Close();
 
 
        // Read the file back in and parse to ensure well formed XML.
        reader = new XmlTextReader (m_Document);
        XmlDocument doc = new XmlDocument();
        // Preserve white space for readability.
        doc.PreserveWhitespace = true;
        //Load the file
        doc.Load(reader);
     
        // Write the XML content to the console.
        Console.Write(doc.InnerXml);
      }

      finally 
      {
        Console.WriteLine();
        Console.WriteLine("Processing of the file {0} complete.", m_Document);
        if (reader != null)
           reader.Close();
        if (writer != null)
           writer.Close();
     } 
   }
 
 }

    

Return to top


Overridden Method: WriteEndAttribute()
Summary
Closes the previous XmlTextWriter.WriteStartAttribute call.
C# Syntax:
public override void WriteEndAttribute();
Remarks
If you call WriteStartAttribute, you can close the attribute with this method.

You can also close the attribute by calling WriteStartAttribute again, calling XmlWriter.WriteAttributeString, or calling XmlTextWriter.WriteEndElement.

Example
The following example writes out a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {

     XmlTextWriter writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     writer.WriteComment("sample XML fragment");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("bookstore");

     //Write the namespace declaration
     writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

     writer.WriteStartElement("book");

     //Lookup the prefix and then write the ISBN attribute
     string prefix = writer.LookupPrefix("urn:samples");
     writer.WriteStartAttribute(prefix, "ISBN", "urn:samples");
     writer.WriteString("1-861003-78");
     writer.WriteEndAttribute();     

     //Write the title
     writer.WriteStartElement("title");
     writer.WriteString("The Handmaid's Tale");
     writer.WriteEndElement();
              
     //Write the price
     writer.WriteElementString("price", "19.95");
     
     //Write the style element
     writer.WriteStartElement(prefix, "style", "urn:samples");
     writer.WriteString("hardcover");
     writer.WriteEndElement();

     //Write the end tag for the book element
     writer.WriteEndElement();

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();

     //Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteEndDocument()
Summary
Closes any open elements or attributes and puts the writer back in the Start state.
C# Syntax:
public override void WriteEndDocument();
Exceptions
Exception Type Condition
XmlException The XML document is invalid.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteEndElement()
Summary
Closes one element and pops the corresponding namespace scope.
C# Syntax:
public override void WriteEndElement();
Remarks
If the element contains no content a short end tag "/>" is written; otherwise a full end tag is written.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type=\"text/xsl\" href=\"book.xsl\"";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h \"hardcover\">");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteEntityRef(
   string name
)
Summary
Writes out an entity reference as follows: & name;.
C# Syntax:
public override void WriteEntityRef(
   string name
);
Parameters:

name

Name of the entity reference.

Exceptions
Exception Type Condition
ArgumentException The text would result in a non-well formed XML document or name is either null or String.Empty.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteFullEndElement()
Summary
Closes one element and pops the corresponding namespace scope.
C# Syntax:
public override void WriteFullEndElement();
Remarks
This method always writes the full end tag. This is useful when dealing with elements that must include a full end tag. For example, browsers expect HTML script blocks to be closed with "</script>".
Example
The following example writes out an element with no content. It uses WriteFullEndElement to write the full end element tag.
using System;
using System.IO;
using System.Xml;

public class Sample
{ 
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("order");

     //Write some attributes.
     writer.WriteAttributeString("date", "2/19/01");
     writer.WriteAttributeString("orderID", "136A5");

     //Write a full end element. Because this element has no
     //content, calling WriteEndElement would have written a
     //short end tag '/>'.
     writer.WriteFullEndElement();
             
     //Write the XML to file and close the writer
     writer.Close();  
  }
}

    

Return to top


Overridden Method: WriteName(
   string name
)
Summary
Writes out the specified name, ensuring it is a valid name according to the W3C XML 1.0 recommendation(http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name ).
C# Syntax:
public override void WriteName(
   string name
);
Parameters:

name

Name to write.

Exceptions
Exception Type Condition
ArgumentException name is not a valid XML name; or name is either null or String.Empty.
Remarks
If XmlTextWriter.Namespaces is set to true, WriteName also checks that the name is also valid according to the W3C Namespaces in XML recommendation.

Return to top


Overridden Method: WriteNmToken(
   string name
)
Summary
Writes out the specified name, ensuring it is a valid NmToken according to the W3C XML 1.0 recommendation(http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
C# Syntax:
public override void WriteNmToken(
   string name
);
Parameters:

name

Name to write.

Exceptions
Exception Type Condition
ArgumentException name is not a valid NmToken; or name is either null or String.Empty.

Return to top


Method: WriteNode(
   XmlReader reader,
   bool defattr
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteNode

Summary
When overridden in a derived class, copies everything from the reader to the writer and moves the reader to the start of the next sibling.
C# Syntax:
public virtual void WriteNode(
   XmlReader reader,
   bool defattr
);
Parameters:

reader

The XmlReader to read from.

defattr

true to copy the default attributes from the XmlReader; otherwise, false.

Exceptions
Exception Type Condition
ArgumentException reader is null.
Remarks
The following table shows the supported node types for this method.

NodeType WriteNode Behavior
Element Writes out the element node and any attribute nodes.
Attribute No operation. Use XmlWriter.WriteStartAttribute or XmlWriter.WriteAttributeString instead.
Text Writes out the text node.
CDATA Writes out the CData section node.
EntityReference Writes out the entity reference node.
ProcessingInstruction Writes out the processing instruction node.
Comment Writes out the comment node.
DocumentType Writes out the document type node.
SignificantWhitespace Writes out the significant whitespace node.
Whitespace Writes out the whitespace node.
EndElement No operation.
EndEntity No operation.
XmlDeclaration Writes out the XML declaration node.

If the reader is in the initial state, this method moves the reader to EOF. If the reader is already at EOF or in a closed state, this method is non-operational.

The following C# code copies an entire XML input document to the console:

              XmlTextReader reader = new XmlTextReader(myfile);
              XmlTextWriter writer = new XmlTextWriter(Console.Out);
              writer.WriteNode(reader, false);
            

Note that if you have moved off the root node and are positioned elsewhere in the document the following C# example correctly writes out the nodes.

              XmlTextReader reader = new XmlTextReader(myfile);
              reader.Read(); // Read PI
              reader.Read(); // Read Comment
              reader.Read(); // Read DOCType
              XmlTextWriter writer = new XmlTextWriter(Console.Out);
              while (!reader.EOF){
               writer.WriteNode(reader, false);
              }
            

If the reader is configured to return whitespace and the writer has XmlTextWriter.Formatting set to "Indented", WriteNode may produce strange output. You will essentially be getting double formatting.

Example
The following example writes the first and last book nodes out to the console.
using System;
using System.IO;
using System.Xml;

public class Sample{

  public static void Main(){

    XmlTextReader reader = new XmlTextReader("books.xml");
    reader.WhitespaceHandling = WhitespaceHandling.None;

    //Move the reader to the first book element.
    reader.MoveToContent();
    reader.Read();

    //Create a writer that outputs to the console.
    XmlTextWriter writer = new XmlTextWriter (Console.Out);
    writer.Formatting = Formatting.Indented;
	
    //Write the start tag.
    writer.WriteStartElement("myBooks");

    //Write the first book.
    writer.WriteNode(reader, false);

    //Skip the second book.
    reader.Skip();

    //Write the last book.
    writer.WriteNode(reader, false);
    writer.WriteEndElement();

    //Close the writer and the reader.
    writer.Close();
    reader.Close();

  }
}

    
The example uses the file, books.xml, as input.
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

    

Return to top


Overridden Method: WriteProcessingInstruction(
   string name,
   string text
)
Summary
Writes out a processing instruction with a space between the name and text as follows: <?name text?>.
C# Syntax:
public override void WriteProcessingInstruction(
   string name,
   string text
);
Parameters:

name

Name of the processing instruction.

text

Text to include in the processing instruction.

Exceptions
Exception Type Condition
ArgumentException The text would result in a non-well formed XML document.

name is either null or String.Empty.

This method is being used to create an XML declaration after XmlTextWriter.WriteStartDocument has already been called.

Remarks
If text is either null or String.Empty, this method writes a ProcessingInstruction with no data content, for example <?name?>.
Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteQualifiedName(
   string localName,
   string ns
)
Summary
Writes out the namespace-qualified name. This method looks up the prefix that is in scope for the given namespace.
C# Syntax:
public override void WriteQualifiedName(
   string localName,
   string ns
);
Parameters:

localName

The local name to write.

ns

The namespace URI to associate with the name.

Exceptions
Exception Type Condition
ArgumentException localName is either null or String.Empty.

localName is not a valid name according to the W3C Namespaces spec.

Remarks
For example, the following C# code:
              writer.Formatting = Formatting.Indented;
              writer.WriteStartElement("root");
               writer.WriteAttributeString("xmlns","x",null,"urn:abc");
               writer.WriteStartElement("item");
               writer.WriteStartAttribute("href",null);
               writer.WriteString("#");
               writer.WriteQualifiedName("test","urn:abc");
               writer.WriteEndAttribute();
               writer.WriteEndElement();
               writer.WriteEndElement();
               writer.Close();
               
            

Generates the following output:

              <root xmlns:x="urn:abc">
               <item href="#x:test"/>
               </root>
               
            

If ns maps to the current default namespace, no prefix is generated.

When writing attribute values, this method generates a prefix if ns is not found. When writing element content, it throws an exception if ns is not found.

If this writer supports namespaces ( XmlTextWriter.Namespaces is set to true), this method also checks that the name is valid according to the W3C Namespaces in XML recommendation (http://www.w3.org/TR/REC-xml-names ).

Example
The following example writes out a portion of a XSD schema.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     //Write an element (this one is the root)
     writer.WriteStartElement("schema");

     //Write the namespace declarations.
     writer.WriteAttributeString("xmlns", null,"http://www.w3.org/2001/XMLSchema");
     writer.WriteAttributeString("xmlns","po",null,"http://contoso.com/po");

     writer.WriteStartElement("element");

     writer.WriteAttributeString("name", "purchaseOrder");

     //Write the type attribute
     writer.WriteStartAttribute(null,"type", null);
     writer.WriteQualifiedName("PurchaseOrder", "http://contoso.com/po");
     writer.WriteEndAttribute();

     writer.WriteEndElement();


     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     // Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);

  }

}

    

Return to top


Overloaded Method: WriteRaw(
   string data
)
Summary
Writes raw markup manually from a string.
C# Syntax:
public override void WriteRaw(
   string data
);
Parameters:

data

String containing the text to write.

Remarks
This method bypasses the entitization of special characters.
Example
The following example writes a string using the WriteRaw method.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
     //Create a writer that outputs to the console.
     XmlTextWriter writer = new XmlTextWriter (Console.Out);
     writer.Formatting = Formatting.Indented;
    
     //Write an element (this one is the root)
     writer.WriteStartElement("Items");

     //Write a string using WriteRaw. Note that the special
     //characters are not entitized.
     writer.WriteStartElement("Item");
     writer.WriteString("Write unentitized text:  ");
     writer.WriteRaw("this & that");
     writer.WriteEndElement();

     //Write the same string using WriteString. Note that the 
     //special characters are entitized.
     writer.WriteStartElement("Item");
     writer.WriteString("Write the same string entitized:  ");
     writer.WriteString("this & that");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
           
     //Write the XML to file and close the writer.
     writer.Close();  
  }

}

    

Return to top


Overloaded Method: WriteRaw(
   char[] buffer,
   int index,
   int count
)
Summary
Writes raw markup manually from a character buffer.
C# Syntax:
public override void WriteRaw(
   char[] buffer,
   int index,
   int count
);
Parameters:

buffer

Character array containing the text to write.

index

The position within the buffer indicating the start of the text to write.

count

The number of characters to write.

Exceptions
Exception Type Condition
ArgumentNullException buffer is null.
ArgumentException The buffer length minus index is less than count.
ArgumentOutOfRangeException index or count is less than zero.
Remarks
This method bypasses the entitization of special characters.

Return to top


Overloaded Method: WriteStartAttribute(
   string localName,
   string ns
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteStartAttribute

Summary
When overridden in a derived class, writes the start of an attribute.
C# Syntax:
public void WriteStartAttribute(
   string localName,
   string ns
);
Parameters:

localName

The local name of the attribute.

ns

The namespace URI of the attribute

Exceptions
Exception Type Condition
ArgumentException localName is either null or String.Empty.
Remarks
This is a more advanced version of XmlWriter.WriteAttributeString that allows you to write an attribute value using multiple write methods, such as XmlWriter.WriteString, XmlWriter.WriteQualifiedName, and so on.
Example
See XmlTextWriter.WriteStartAttribute (in the XmlTextWriter class) for an example using this method.
See also:
XmlWriter.WriteEndAttribute

Return to top


Overloaded Method: WriteStartAttribute(
   string prefix,
   string localName,
   string ns
)
Summary
Writes the start of an attribute.
C# Syntax:
public override void WriteStartAttribute(
   string prefix,
   string localName,
   string ns
);
Parameters:

prefix

Namespace prefix of the attribute.

localName

LocalName of the attribute.

ns

NamespaceURI of the attribute

Exceptions
Exception Type Condition
ArgumentException localName is either null or String.Empty.
Remarks
This is a more advanced version of XmlWriter.WriteAttributeString that allows you to write an attribute value using multiple write methods, such as XmlTextWriter.WriteString.
Example
The following example writes out a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {

     XmlTextWriter writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     writer.WriteComment("sample XML fragment");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("bookstore");

     //Write the namespace declaration
     writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

     writer.WriteStartElement("book");

     //Lookup the prefix and then write the ISBN attribute
     string prefix = writer.LookupPrefix("urn:samples");
     writer.WriteStartAttribute(prefix, "ISBN", "urn:samples");
     writer.WriteString("1-861003-78");
     writer.WriteEndAttribute();     

     //Write the title
     writer.WriteStartElement("title");
     writer.WriteString("The Handmaid's Tale");
     writer.WriteEndElement();
              
     //Write the price
     writer.WriteElementString("price", "19.95");
     
     //Write the style element
     writer.WriteStartElement(prefix, "style", "urn:samples");
     writer.WriteString("hardcover");
     writer.WriteEndElement();

     //Write the end tag for the book element
     writer.WriteEndElement();

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();

     //Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    
See also:
XmlTextWriter.WriteEndAttribute

Return to top


Overloaded Method: WriteStartDocument()
Summary
Writes the XML declaration with the version "1.0".
C# Syntax:
public override void WriteStartDocument();
Exceptions
Exception Type Condition
InvalidOperationException This is not the first write method called after the constructor.
Remarks
The encoding level of the document is determined by how the writer is implemented. For example, if an Encoding object is specified in the XmlTextWriter constructor, this determines the value of the encoding attribute. This method does not create a standalone attribute.

When WriteStartDocument is called the writer validates that what you are writing is a well-formed XML document. For example, it checks that the XML declaration is the first node, that one and only one root-level element exists and so on. If this method is not called, the writer assumes an XML fragment is being written and applies no root level rules.

If WriteStartDocument has been called and then the XmlTextWriter.WriteProcessingInstruction method is used to create another XML declaration, an exception will be thrown.

Example
The following example writes an XML file representing a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {
     XmlTextWriter writer = null;

     writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;

     //Write the XML delcaration 
     writer.WriteStartDocument();

     //Write the ProcessingInstruction node
     String PItext="type='text/xsl' href='book.xsl'";
     writer.WriteProcessingInstruction("xml-stylesheet", PItext);

     //Write the DocumentType node
     writer.WriteDocType("book", null , null, "<!ENTITY h 'hardcover'>");
        
     //Write a Comment node
     writer.WriteComment("sample XML");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("book");

     //Write the genre attribute
     writer.WriteAttributeString("genre", "novel");
    
     //Write the ISBN attribute
     writer.WriteAttributeString("ISBN", "1-8630-014");

     //Write the title
     writer.WriteElementString("title", "The Handmaid's Tale");
              
     //Write the style element
     writer.WriteStartElement("style");
     writer.WriteEntityRef("h");
     writer.WriteEndElement(); 

     //Write the price
     writer.WriteElementString("price", "19.95");

     //Write CDATA
     writer.WriteCData("Prices 15% off!!");

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     writer.WriteEndDocument();

     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();  

     //Load the file into an XmlDocument to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);  
    
     //Display the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overloaded Method: WriteStartDocument(
   bool standalone
)
Summary
Writes the XML declaration with the version "1.0" and the standalone attribute.
C# Syntax:
public override void WriteStartDocument(
   bool standalone
);
Parameters:

standalone

If true, it writes "standalone=yes"; if false, it writes "standalone=no"

Exceptions
Exception Type Condition
InvalidOperationException This is not the first write method called after the constructor.
Remarks
The encoding level of the document is determined by how the writer is implemented. For example, if an Encoding object is specified in the XmlTextWriter constructor, this determines the value of the encoding attribute.

When WriteStartDocument is called the writer validates that what you are writing is a well-formed XML document. For example, it checks that the XML declaration is the first node, that one and only one root-level element exists and so on. If this method is not called, the writer assumes an XML fragment is being written and applies no root level rules.

If WriteStartDocument has been called and then the XmlTextWriter.WriteProcessingInstruction method is used to create another XML declaration, an exception will be thrown.

Return to top


Overloaded Method: WriteStartElement(
   string localName
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteStartElement

Summary
When overridden in a derived class, writes out a start tag with the specified local name.
C# Syntax:
public void WriteStartElement(
   string localName
);
Parameters:

localName

The local name of the element.

Exceptions
Exception Type Condition
InvalidOperationException The writer is closed.
Example
The following example writes an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer.
     writer.Close();  

  }

}

    

Return to top


Overloaded Method: WriteStartElement(
   string localName,
   string ns
)
Inherited
See base class member description: System.Xml.XmlWriter.WriteStartElement

Summary
When overridden in a derived class, writes the specified start tag and associates it with the given namespace.
C# Syntax:
public void WriteStartElement(
   string localName,
   string ns
);
Parameters:

localName

The local name of the element. The local name of the element.

ns

The namespace URI to associate with the element. If this namespace is already in scope and has an associated prefix, the writer automatically writes that prefix also. The namespace URI to associate with the element. If this namespace is already in scope and has an associated prefix, the writer automatically writes that prefix also.

Exceptions
Exception Type Condition
InvalidOperationException The writer is closed.
Remarks
After calling this method you can either write attributes, or create content using XmlWriter.WriteComment, XmlWriter.WriteString, or WriteStartElement for child elements. You can close the element with either XmlWriter.WriteEndElement or XmlWriter.WriteFullEndElement. For example, the following C# code
              writer.WriteStartElement("item",null);
              writer.WriteString("some text");
              writer.WriteEndElement();
                 
            

generates the following output:

              <item>some text</item>
                 
            
Example
See XmlTextWriter.WriteStartElement (in the XmlTextWriter class) for an example using this method.

Return to top


Overloaded Method: WriteStartElement(
   string prefix,
   string localName,
   string ns
)
Summary
Writes the specified start tag and associates it with the given namespace and prefix.
C# Syntax:
public override void WriteStartElement(
   string prefix,
   string localName,
   string ns
);
Parameters:

prefix

The namespace prefix of the element.

localName

The local name of the element. The local name of the element.

ns

The namespace URI to associate with the element. If this namespace is already in scope and has an associated prefix then the writer will automatically write that prefix also. The namespace URI to associate with the element. If this namespace is already in scope and has an associated prefix then the writer will automatically write that prefix also.

Exceptions
Exception Type Condition
InvalidOperationException The writer is closed.
Remarks
After calling this method you can either write attributes or create content using XmlTextWriter.WriteComment, XmlTextWriter.WriteString, or XmlTextWriter.WriteStartElement for child elements. You can close the element with XmlTextWriter.WriteEndElement at which time an end tag is written out.
Example
The following example writes out a book.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  private const string filename = "sampledata.xml";

  public static void Main()
  {

     XmlTextWriter writer = new XmlTextWriter (filename, null);
     //Use indenting for readability
     writer.Formatting = Formatting.Indented;
        
     writer.WriteComment("sample XML fragment");
    
     //Write an element (this one is the root)
     writer.WriteStartElement("bookstore");

     //Write the namespace declaration
     writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

     writer.WriteStartElement("book");

     //Lookup the prefix and then write the ISBN attribute
     string prefix = writer.LookupPrefix("urn:samples");
     writer.WriteStartAttribute(prefix, "ISBN", "urn:samples");
     writer.WriteString("1-861003-78");
     writer.WriteEndAttribute();     

     //Write the title
     writer.WriteStartElement("title");
     writer.WriteString("The Handmaid's Tale");
     writer.WriteEndElement();
              
     //Write the price
     writer.WriteElementString("price", "19.95");
     
     //Write the style element
     writer.WriteStartElement(prefix, "style", "urn:samples");
     writer.WriteString("hardcover");
     writer.WriteEndElement();

     //Write the end tag for the book element
     writer.WriteEndElement();

     //Write the close tag for the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Flush();
     writer.Close();

     //Read the file back in and parse to ensure well formed XML
     XmlDocument doc = new XmlDocument();
     //Preserve white space for readability
     doc.PreserveWhitespace = true;
     //Load the file
     doc.Load(filename);
    
     //Write the XML content to the console
     Console.Write(doc.InnerXml);  

  }

}

    

Return to top


Overridden Method: WriteString(
   string text
)
Summary
Writes the given text content.
C# Syntax:
public override void WriteString(
   string text
);
Parameters:

text

Text to write.

Exceptions
Exception Type Condition
ArgumentException The text string contains an invalid surrogate pair.
Remarks
WriteString does the following

For example, this input string test<item>test is written as

              test&lt;item&gt;test
            

If text is either null or String.Empty, this method writes a text node with no data content.

Example
The following example writes an XML fragment.
using System;
using System.IO;
using System.Xml;

public class Sample
{
  
  public static void Main()
  {
     //Create a writer to write XML to the console.
     XmlTextWriter writer = null;
     writer = new XmlTextWriter (Console.Out);

     //Use indentation for readability.
     writer.Formatting = Formatting.Indented;
     writer.Indentation = 4;
        
     //Write an element (this one is the root).
     writer.WriteStartElement("book");

     //Write the title element.
     writer.WriteStartElement("title");
     writer.WriteString("Pride And Prejudice");
     writer.WriteEndElement();

     //Write the close tag for the root element.
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer.
     writer.Close();  

  }

}

    

Return to top


Overridden Method: WriteSurrogateCharEntity(
   char lowChar,
   char highChar
)
Summary
Generates and writes the surrogate character entity for the surrogate character pair.
C# Syntax:
public override void WriteSurrogateCharEntity(
   char lowChar,
   char highChar
);
Parameters:

lowChar

The low surrogate. This must be a value between 0xDC00 and 0xDFFF.

highChar

The high surrogate. This must be a value between 0xD800 and 0xDBFF.

Exceptions
Exception Type Condition
Exception An invalid surrogate character pair was passed.
Remarks
This method is only applicable on systems that use UTF-16 encoding.

The surrogate character entity is written in hexadecimal format. The range for surrogate characters is #x10000 to #x10FFFF. The following formula is used to generate the surrogate character entity: (highChar -0xD800) * 0x400 + (lowChar -0xDC00) + 0x10000

For both HTML and XML, the document character set (and therefore the notation of numeric character references) is based on UCS [ISO-10646]. A single numeric character reference in a source document may therefore in some cases correspond to two 16-bit units in a string (a high surrogate and a low surrogate). These 16-bit units are referred to as a surrogate pair.

For more information regarding surrogates or characters, refer to section 3.7 of the Unicode 3.0/Unicode 2.0 standard located at http://www.unicode.org, or section 2.2 of the W3C XML 1.0 Recommendation located at http://www.w3.org/TR/REC-xml#charsets .

Return to top


Overridden Method: WriteWhitespace(
   string ws
)
Summary
Writes out the given white space.
C# Syntax:
public override void WriteWhitespace(
   string ws
);
Parameters:

ws

The string of white space characters.

Exceptions
Exception Type Condition
ArgumentException The string contains non-white space characters.
Remarks
This method is used to manually format your document. Use the XmlTextWriter.Formatting property to have the writer format the output automatically.
Example
The following example uses the WriteWhitespace method to control how the file is formatted.
using System;
using System.IO;
using System.Xml;

public class Sample
{  
  public static void Main()
  {
    // Create the writer.
    XmlTextWriter writer = null;
    writer = new XmlTextWriter ("ws.html", null);

    // Write an element (this one is the root).
    writer.WriteStartElement("p");

    // Write the xml:space attribute.
    writer.WriteAttributeString("xml", "space", null, "preserve");

    // Verify that xml:space is set properly.
    if (writer.XmlSpace == XmlSpace.Preserve)
      Console.WriteLine("xmlspace is correct!");

    // Write out the HTML elements.  Insert white space
    // between 'something' and 'Big'
    writer.WriteString("something");
    writer.WriteWhitespace("  ");
    writer.WriteElementString("b", "B");
    writer.WriteString("ig");

    // Write the root end element.
    writer.WriteEndElement();
             
    // Write the XML to file and close the writer.
    writer.Close();  
  }
}

    
See also:
XmlTextWriter.Formatting

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.