public class XmlTextWriter : XmlWriter
|
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.
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. |
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. |
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.WriteAttributeStringWhen 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.WriteAttributeStringWhen 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.WriteAttributeStringWhen 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.WriteElementStringWhen 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.WriteElementStringWhen 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.WriteStartAttributeWhen 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.WriteStartElementWhen 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.WriteStartElementWhen 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. |
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:
public XmlTextWriter( |
w
w
encoding
Exception Type | Condition |
---|---|
ArgumentException | The encoding is not supported or the stream cannot be written to. |
filename
encoding
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. |
public Stream BaseStream {get;}
|
public Formatting Formatting {get; set;}
|
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.
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(); } }
public int Indentation {get; set;}
|
Exception Type | Condition |
---|---|
ArgumentException | Setting this property to a negative value. |
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);
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(); } }
public char IndentChar {get; set;}
|
public bool Namespaces {get; set;}
|
Exception Type | Condition |
---|---|
InvalidOperationException | You can only change this property when in the WriteState.Start state. |
public char QuoteChar {get; set;}
|
Exception Type | Condition |
---|---|
ArgumentException | Setting this property to something other than either a single or double quote. |
public override WriteState WriteState {get;}
|
public override string XmlLang {get;}
|
public override XmlSpace XmlSpace {get;}
|
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(); } }
public override 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. |
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(); } }
~XmlTextWriter(); |
public override void Flush(); |
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(); } }
public virtual int GetHashCode(); |
public Type GetType(); |
ns
Exception Type | Condition |
---|---|
ArgumentException | ns is either null or String.Empty. |
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); } }
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. |
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"); } }
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 override void WriteCData( |
text
Exception Type | Condition |
---|---|
ArgumentException | The text would result in a non-well formed XML document. |
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); } }
public override void WriteCharEntity( |
ch
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. |
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(); } } }
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 override void WriteComment( |
text
Exception Type | Condition |
---|---|
ArgumentException | The text would result in a non-well formed XML document |
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); } }
public override 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. |
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); } }
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 override void WriteEndAttribute(); |
You can also close the attribute by calling WriteStartAttribute again, calling XmlWriter.WriteAttributeString, or calling XmlTextWriter.WriteEndElement.
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); } }
public override void WriteEndDocument(); |
Exception Type | Condition |
---|---|
XmlException | The XML document is invalid. |
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); } }
public override void WriteEndElement(); |
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); } }
public override void WriteEntityRef( |
name
Exception Type | Condition |
---|---|
ArgumentException | The text would result in a non-well formed XML document or name is either null or String.Empty. |
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); } }
public override void WriteFullEndElement(); |
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(); } }
public override void WriteName( |
name
Exception Type | Condition |
---|---|
ArgumentException | name is not a valid XML name; or name is either null or String.Empty. |
public override 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 XmlTextWriter.WriteStartDocument has already been called. |
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); } }
localName
ns
Exception Type | Condition |
---|---|
ArgumentException | localName is either null or String.Empty. localName is not a valid name according to the W3C Namespaces spec. |
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 ).
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 override void WriteRaw( |
data
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(); } }
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. |
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); } }
public override 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 XmlTextWriter.WriteProcessingInstruction method is used to create another XML declaration, an exception will be thrown.
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); } }
public override 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 XmlTextWriter.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. |
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); } }
public override 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 as
test<item>test
If text is either null or String.Empty, this method writes a text node with no data content.
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(); } }
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 override void WriteWhitespace( |
ws
Exception Type | Condition |
---|---|
ArgumentException | The string contains non-white space characters. |
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(); } }