Writing xml:space and xml:lang AttributesThe WriteAttributeString method can also be used to write the special XML attributes xml:space and xml:lang . The xml:space attribute determines how white space should be handled within an element's scope. The xml:space attribute has only two possible values: preserve and default . default signals that the parse's white-space processing mode is acceptable for this element. preserve means that all the white space in the element's scope, significant or insignificant, should be preserved. When setting the value of the xml:space attribute, the XmlTextWriter will verifiy that the value is equal to one of the two strings. If it isn't, a System.InvalidOperationException is raised. The xml:lang attribute specifies the language of the text content within the element's scope. This can be helpful when reading XML data that may be written in multiple languages. The XmlTextWriter makes no attempt to verify that the attribute value is valid. Listing 10.27 demonstrates how to set values for both special attributes.
Listing 10.27C# public static void Main() { XmlTextWriter writer = new XmlTextWriter("nsdecl.xml", Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartElement("root"); // set the xml:space attribute to preserver writer.WriteAttributeString("xml", "space", null, "preserve"); // set the xml:lang attribute to lang:en writer.WriteAttributeString("xml", "lang", null, "en"); writer.WriteEndElement(); writer.Close(); } VB sub Main() Dim writer As New XmlTextWriter("nsdecl.xml", Encoding.UTF8) writer.Formatting = Formatting.Indented writer.WriteStartElement("root") ' set the xml:space attribute to preserve writer.WriteAttributeString("xml", _ "space", _ nothing, _ "preserve") ' set the xml:lang attribute to lang:en writer.WriteAttributeString("xml", _ "lang", _ nothing, _ "en") writer.WriteEndElement() writer.Close() End Sub Output <root xml:space="preserve" xml:lang="en" /> The xml:space attribute is set to preserve by calling WriteAttributeString and specifying "xml" as the prefix, "space" as the attribute's local name, null as the namespace, and "preserve" as the attribute value. The xml:lang attribute is set to en , almost exactly as we set xml:space , except that the attribute's local name was "lang" and the value was "en" . |