Writing White-Space Characters


There may be times when you need to format your document manually. The WriteWhitespace method can be used to write white space to your XML document. It is important to note that for the white space to be considered significant, the containing element should have the xml:space attribute value set to preserve . This is because significant white space is defined as any white space inside a mixed content model or any white space inside the scope of an xml:space="preserve" attribute. The xml:space attribute can appear on any element, but an element's content model can be marked as a mixed content only in the document's DTD. Since the XmlTextReader does not recognize DTD information, the only way to mark white space as significant is to put it in the scope of an xml:space="preserve" attribute. Listing 10.36 demonstrates how to utilize WriteWhitespace effectively.

Listing 10.36
 C# static void Main() {   XmlTextWriter writer =     new XmlTextWriter("ws.xml", Encoding.UTF8);   writer.WriteStartDocument();   writer.WriteStartElement("Root");   writer.WriteAttributeString("xml", "space", "", "preserve");   writer.WriteWhitespace("\t");   writer.WriteElementString("bogus", "after white space");   writer.WriteEndElement();   writer.Close();   XmlTextReader reader = new XmlTextReader("ws.xml");   reader.WhitespaceHandling = WhitespaceHandling.Significant;   while(reader.Read())   {     MessageBox.Show("Node Type: " + reader.NodeType);     MessageBox.Show("Value: " + reader.Value);   }   reader.Close(); } VB sub Main()   Dim writer As _     New XmlTextWriter("ws.xml", Encoding.UTF8)   writer.WriteStartDocument()   writer.WriteStartElement("Root")   writer.WriteAttributeString("xml", "space", "", "preserve")   writer.WriteWhitespace(Chr(9))   writer.WriteElementString("bogus", "after white space")   writer.WriteEndElement()   writer.Close()   XmlTextReader reader = new XmlTextReader("ws.xml")   reader.WhitespaceHandling = WhitespaceHandling.Significant   While(reader.Read())     MessageBox.Show("Node Type: " & reader.NodeType)     MessageBox.Show("Value: " & reader.Value)   End While   reader.Close() End Sub 


Microsoft.NET Compact Framework Kick Start
Microsoft .NET Compact Framework Kick Start
ISBN: 0672325705
EAN: 2147483647
Year: 2003
Pages: 206

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net