public abstract class XmlWriter
|
XmlWriter maintains a namespace stack corresponding to all the namespaces defined in the current element stack. Using XmlWriter 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.XmlWriter 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>
XmlWriter 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, XmlWriter 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, XmlWriter 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.
WriteState | Read-only When overridden in a derived class, gets the state of the writer. |
XmlLang | Read-only When overridden in a derived class, gets the current xml:lang scope. |
XmlSpace | Read-only When overridden in a derived class, gets an XmlSpace representing the current xml:space scope. |
Close | When overridden in a derived class, 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 | When overridden in a derived class, 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 | When overridden in a derived class, 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 | When overridden in a derived class, writes out all the attributes found at the current position in the XmlReader. |
WriteAttributeString | Overloaded:WriteAttributeString(string localName, string value) When overridden in a derived class, writes out the attribute with the specified local name and value. |
WriteAttributeString | Overloaded:WriteAttributeString(string localName, string ns, string value) When overridden in a derived class, writes an attribute with the specified parameters. |
WriteAttributeString | Overloaded:WriteAttributeString(string prefix, string localName, string ns, string value) When overridden in a derived class, writes out the attribute with the specified prefix, local name, namespace URI and value. |
WriteBase64 | When overridden in a derived class, encodes the specified binary bytes as base64 and writes out the resulting text. |
WriteBinHex | When overridden in a derived class, encodes the specified binary bytes as binhex and writes out the resulting text. |
WriteCData | When overridden in a derived class, writes out a <![CDATA[...]]> block containing the specified text. |
WriteCharEntity | When overridden in a derived class, forces the generation of a character entity for the specified Unicode character value. |
WriteChars | When overridden in a derived class, writes text a buffer at a time. |
WriteComment | When overridden in a derived class, writes out a comment <!--...--> containing the specified text. |
WriteDocType | When overridden in a derived class, writes the DOCTYPE declaration with the specified name and optional attributes. |
WriteElementString | Overloaded:WriteElementString(string localName, string value) When overridden in a derived class, writes an element with the specified local name and value. |
WriteElementString | Overloaded:WriteElementString(string localName, string ns, string value) When overridden in a derived class, writes an element with the specified parameters. |
WriteEndAttribute | When overridden in a derived class, closes the previous XmlWriter.WriteStartAttribute call. |
WriteEndDocument | When overridden in a derived class, closes any open elements or attributes and puts the writer back in the Start state. |
WriteEndElement | When overridden in a derived class, closes one element and pops the corresponding namespace scope. |
WriteEntityRef | When overridden in a derived class, writes out an entity reference as follows: & name;. |
WriteFullEndElement | When overridden in a derived class, closes one element and pops the corresponding namespace scope. |
WriteName | When overridden in a derived class, 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 | When overridden in a derived class, 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 | 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 | When overridden in a derived class, writes out a processing instruction with a space between the name and text as follows: <?name text?>. |
WriteQualifiedName | When overridden in a derived class, 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) When overridden in a derived class, writes raw markup manually from a string. |
WriteRaw | Overloaded:WriteRaw(char[] buffer, int index, int count) When overridden in a derived class, writes raw markup manually from a character buffer. |
WriteStartAttribute | Overloaded:WriteStartAttribute(string localName, string ns) When overridden in a derived class, writes the start of an attribute. |
WriteStartAttribute | Overloaded:WriteStartAttribute(string prefix, string localName, string ns) When overridden in a derived class, writes the start of an attribute. |
WriteStartDocument | Overloaded:WriteStartDocument() When overridden in a derived class, writes the XML declaration with the version "1.0". |
WriteStartDocument | Overloaded:WriteStartDocument(bool standalone) When overridden in a derived class, writes the XML declaration with the version "1.0" and the standalone attribute. |
WriteStartElement | Overloaded:WriteStartElement(string localName) When overridden in a derived class, writes out a start tag with the specified local name. |
WriteStartElement | Overloaded:WriteStartElement(string localName, string ns) 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) When overridden in a derived class, writes the specified start tag and associates it with the given namespace and prefix. |
WriteString | When overridden in a derived class, writes the given text content. |
WriteSurrogateCharEntity | When overridden in a derived class, generates and writes the surrogate character entity for the surrogate character pair. |
WriteWhitespace | When overridden in a derived class, writes out the given white space. |
ctor #1 | Default constructor. This constructor is called by derived class constructors to initialize state in this type. |
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:
protected XmlWriter(); |
public abstract WriteState WriteState {get;}
|
public abstract string XmlLang {get;}
|
public abstract XmlSpace XmlSpace {get;}
|
public abstract void Close(); |
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. |
~XmlWriter(); |
public abstract void Flush(); |
public virtual int GetHashCode(); |
public Type GetType(); |
ns
Exception Type | Condition |
---|---|
ArgumentException | ns is either null or String.Empty. |
protected object MemberwiseClone(); |
public virtual string ToString(); |
reader
defattr
Exception Type | Condition |
---|---|
ArgumentException | reader is null. |
XmlException | The reader is not positioned on either an element, attribute or XmlDeclaration node. |
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 > entity that has been expanded, to ensure a well-formed document the expanded ">" is replaced when written out with >.
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>
localName
value
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. |
localName
ns
value
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. |
WriteAttributeString does the following
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); } }
public void WriteAttributeString( |
prefix
localName
ns
value
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. |
WriteAttributeString does the following
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); } }
buffer
index
count
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. |
buffer
index
count
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. |
public abstract void WriteCData( |
text
Exception Type | Condition |
---|---|
ArgumentException | The text would result in a non-well formed XML document. |
public abstract void WriteCharEntity( |
ch
Exception Type | Condition |
---|---|
ArgumentException | The character is in the surrogate pair character range, 0xd800 - 0xdfff. |
buffer
index
count
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. |
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();
public abstract void WriteComment( |
text
Exception Type | Condition |
---|---|
ArgumentException | The text would result in a non-well formed XML document. |
public abstract void WriteDocType( |
name
pubid
sysid
subset
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. |
localName
value
Exception Type | Condition |
---|---|
InvalidOperationException | This results in an invalid XML document. |
ArgumentException | localName is either null or String.Empty. |
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(); } } }
localName
ns
value
Exception Type | Condition |
---|---|
InvalidOperationException | This results in an invalid XML document. |
ArgumentException | localName is either null or String.Empty. |
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(); } } }
public abstract void WriteEndAttribute(); |
You can also close the attribute by calling WriteStartAttribute again, calling XmlWriter.WriteAttributeString, or calling XmlWriter.WriteEndElement.
public abstract void WriteEndDocument(); |
Exception Type | Condition |
---|---|
XmlException | The XML document is invalid. |
public abstract void WriteEndElement(); |
Exception Type | Condition |
---|---|
InvalidOperationException | This results in an invalid XML document. |
public abstract void WriteEntityRef( |
name
Exception Type | Condition |
---|---|
ArgumentException | name is either null or String.Empty. |
public abstract void WriteFullEndElement(); |
public abstract void WriteName( |
name
Exception Type | Condition |
---|---|
ArgumentException | name is not a valid XML name; or name is either null or String.Empty. |
public abstract void WriteNmToken( |
name
Exception Type | Condition |
---|---|
ArgumentException | name is not a valid NmToken; or name is either null or String.Empty. |
reader
defattr
Exception Type | Condition |
---|---|
ArgumentException | reader is null. |
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.
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>
name
text
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 XmlWriter.WriteStartDocument has already been called. |
XmlTextWriter writer = new XmlTextWriter("pi.xml", Encoding.UTF8); writer.WriteProcessingInstruction("xml", "version='1.0', encoding='UTF-16'"); writer.WriteStartElement("root"); writer.Close();If text is either null or String.Empty, this method writes a ProcessingInstruction with no data content, for example <?name?>.
localName
ns
Exception Type | Condition |
---|---|
ArgumentException | localName is either null or String.Empty. localName is not a valid name. |
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.
public abstract void WriteRaw( |
data
buffer
index
count
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. |
localName
ns
Exception Type | Condition |
---|---|
ArgumentException | localName is either null or String.Empty. |
prefix
localName
ns
Exception Type | Condition |
---|---|
ArgumentException | localName is either null or String.Empty. |
public abstract void WriteStartDocument(); |
Exception Type | Condition |
---|---|
InvalidOperationException | This is not the first write method called after the constructor. |
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 XmlWriter.WriteProcessingInstruction method is used to create another XML declaration, an exception will be thrown.
public abstract void WriteStartDocument( |
standalone
Exception Type | Condition |
---|---|
InvalidOperationException | This is not the first write method called after the constructor. |
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 XmlWriter.WriteProcessingInstruction method is used to create another XML declaration, an exception will be thrown.
public void WriteStartElement( |
localName
Exception Type | Condition |
---|---|
InvalidOperationException | The writer is closed. |
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(); } }
localName
ns
Exception Type | Condition |
---|---|
InvalidOperationException | The writer is closed. |
writer.WriteStartElement("item",null); writer.WriteString("some text"); writer.WriteEndElement();
generates the following output:
<item>some text</item>
prefix
localName
ns
Exception Type | Condition |
---|---|
InvalidOperationException | The writer is closed. |
public abstract void WriteString( |
text
Exception Type | Condition |
---|---|
ArgumentException | The text string contains an invalid surrogate pair. |
For example, this input string
test<item>test
is written out as
test<item>test
If text is either null or String.Empty, this method writes a text node with no data content.
lowChar
highChar
Exception Type | Condition |
---|---|
Exception | An invalid surrogate character pair was passed. |
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 .
public abstract void WriteWhitespace( |
ws
Exception Type | Condition |
---|---|
ArgumentException | The string contains non-white space characters. |