写入类型化数据

通过 XmlWriter 类可以写出类型化数据。 WriteValue 方法接受公共语言运行库 (CLR) 简单类型化的值。 在处理 CLR 简单类型和 XmlWriter 实例时,此功能非常有用。 可以调用 WriteValue 方法来写出类型化值,而不是在 XmlConvert 类上使用方法,在写出之前将类型化值转换为字符串值。

写出类型化值

WriteValue 方法使用 CLR 对象并使用 XML 架构定义语言 (XSD) 数据类型转换规则将输入值转换为所需的输出类型。 如果 CLR 对象是列表类型,例如 IEnumerableIListICollection,将作为值类型数组对待。

在调用 WriteValue 方法时,XmlWriter 根据 XML 架构 (XSD) 数据类型定义将值转换为其字符串表示形式并使用 WriteString 方法写出。

写入到文本

在调用 WriteValue 时,类型化值将使用该架构类型的 XmlConvert 规则序列化为文本。

CLR 类型

默认的 XML 架构 (XSD) 数据类型

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

**这些类型不符合 CLS。 这些类型在 XmlReader 类上没有对应的方法。

注意注意

如果继续多次调用 WriteValue,值不会通过空格分隔。必须在调用 WriteValue 之间调用 WriteWhitespace,以插入空白。

写入到 XML 数据存储

XmlWriter 可以用于写入到 XML 数据存储。 例如,XPathNavigator 类可以创建一个 XmlWriter 对象,用于为 XmlDocument 对象创建节点。

如果数据存储包含可用的架构信息,若 WriteValue 调用尝试转换不允许的类型WriteValue 方法,将引发异常。

如果数据存储未包含可用的架构信息,WriteValue 方法将所有值作为 xsd:anySimpleType 类型对待。

示例

以下示例将图书价格提高 15%,然后再写出。 架构信息从读取器中获取,读取器是一个验证 XmlReader 对象。

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();

请参见

其他资源

用 XmlWriter 编写 XML

System.Xml 类中的类型支持