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("	");
  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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.141.115