Controlling White-Space Interpretation with the WhitespaceHandling Property

The WhitespaceHandling property provides read and write access to a value that determines how white space will be handled. The WhitespaceHandling property takes an enumeration value of type System.Xml.WhitespaceHandling. Table 10.1 shows the WhitespaceHandling values and how they affect the XmlTextReader.

Table 10.1. The WhitespaceHandling Enumeration Values and Meanings
VALUEEFFECT ON XmlTextReader
AllBoth Whitespace and SignificantWhitespace nodes are returned.
NoneNo Whitespace or SignificantWhitespace nodes are returned.
SignificantOnly SignificantWhitespace is returned.

The WhitespaceHandling property can be changed at any time while parsing and will take effect on the next read operation. But attempting to change this property when the reader is closed would raise an InvalidOperationException. The default value of the WhitespaceHandling property is WhitespaceHandling.All.

SignificantWhitespace nodes are returned only when the node is within the xml:space attribute that is set to “preserve,” because there is no DTD available. Listing 10.6 demonstrates how the XmlTextReader parses XML when the WhitespaceHandling property is set to different values.

Listing 10.6.
C#
public static void Main(string[] args)
{
     ReadXml(WhitespaceHandling.None);
     ReadXml(WhitespaceHandling.All);
     ReadXml(WhitespaceHandling.Significant);
}

public static void
ReadXml(WhitespaceHandling ws)
{
     XmlTextReader reader = new XmlTextReader("input.xml");
     reader.WhitespaceHandling = ws;

     while(reader.Read())
     {
       case XmlNodeType.Whitespace:
         MessageBox.Show("Whitespace");
         break;
       case XmlNodeType.SignificantWhitespace:

         MessageBox.Show("SignificantWhitespace");
         break;
       case XmlNodeType.Element:
         MessageBox.Show("Node " + reader.Name);
         break;
     }
     reader.Close();
}

VB
Sub Main()
  ReadXml(WhitespaceHandling.None)
  ReadXml(WhitespaceHandling.All)
  ReadXml(WhitespaceHandling.Significant)
End Sub

Sub ReadXml(ByVal ws As WhitespaceHandling)
   Dim reader As New XmlTextReader("input.xml")
   reader.WhitespaceHandling = ws

   While (reader.Read())
     If (reader.NodeType = XmlNodeType.Whitespace) Then
        MessageBox.Show("Whitespace")
     ElseIf (reader.NodeType = XmlNodeType.SignificantWhitespace)
     Then
        MessageBox.Show("SignificantWhitespace")
     ElseIf (reader.NodeType = XmlNodeType.Element) Then
        MessageBox.Show("Element")
     End If
   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.142.114.19