Controlling White-Space Interpretation with the WhitespaceHandling Property


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

VALUE

EFFECT ON XmlTextReader

All

Both Whitespace and S ignificantWhitespace 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.

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 


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