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.
VALUE | EFFECT ON XmlTextReader |
---|---|
All | Both Whitespace and SignificantWhitespace nodes are returned. |
None | No Whitespace or SignificantWhitespace nodes are returned. |
Significant | Only 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.
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 |
3.128.226.255