Writing Typed Data
The XmlWriter class provides the ability to write typed data. The WriteValue method accepts common language runtime (CLR) simple-typed values. This ability is useful when dealing with CLR simple-types and an XmlWriter instance. You can call the WriteValue method to write the typed value, rather than using the methods on the XmlConvert class to convert the typed data to a string value before writing it out.
Writing Typed Values
The WriteValue method takes a CLR object and converts the input value to the desired output type using the XML Schema definition language (XSD) data type conversion rules. If the CLR object is a list type, such as IEnumerable, IList, or ICollection, it is treated as an array of the value type.
When the WriteValue method is called, the XmlWriter converts the value to its string representations according to the XML Schema (XSD) data type rules and writes it out using the WriteString method.
Writing to Text
When WriteValue is called, the typed value is serialized to text using the XmlConvert rules for that schema type.
CLR Type |
Default XML Schema (XSD) Data Type |
---|---|
System.Boolean |
xsd:boolean |
System.Byte** |
xsd:integer |
System.Byte[] |
xsd:base64Binary |
System.Char** |
xsd:string |
System.DateTime |
xsd:dateTime |
System.Decimal |
xsd:decimal |
System.Double |
xsd:double |
System.Int16** |
xsd:integer |
System.Int32 |
xsd:integer |
System.Int64 |
xsd:integer |
System.Single |
xsd:float |
System.String |
xsd:string |
System.IO.TextReader |
xsd:string |
System.IO.BinaryReader |
xsd:base64Binary |
**These types are not CLS-compliant. They do not have a corresponding method on the XmlReader class.
Note
If WriteValue is called multiple times in succession, the values are not delimited by a space. You must call WriteWhitespace between calls to WriteValue to insert white space.
Writing to an XML Data Store
The XmlWriter can be used to write to an XML data store. For example, the XPathNavigator class can create an XmlWriter object to create nodes for an XmlDocument object.
If the data store has schema information available to it, the WriteValue method throws an exception if the WriteValue call attempts to convert to a type that is not allowed.
If the data store does not have schema information available to it, the WriteValue method treats all values as an xsd:anySimpleType type.
Example
The following example raises the book price by 15 percent before writing it out. The schema information is obtained from the reader, which is a validating XmlReader object.
reader.ReadToDescendant("price")
writer.WriteStartElement("price")
writer.WriteValue(reader.ReadElementContentAsDouble() * 1.15)
writer.WriteEndElement()
reader.ReadToDescendant("price");
writer.WriteStartElement("price");
writer.WriteValue((reader.ReadElementContentAsDouble()) * 1.15);
writer.WriteEndElement();