共用方式為


撰寫具型別的資料

更新: November 2007

XmlWriter 類別提供寫入具型別資料的功能。WriteValue 方法可接受 Common Language Runtime (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 類別中的型別支援