2014-09-26 273 views
1

我具有存儲在SQL Server作爲xml類型,這是一個int值SqlXml當在C#反序列化到對象

在數據庫中的值檢索到:

<int>1234</int> 

我怎樣才能反序列化該值到價值1234int

+0

看到這個[鏈接](http://stackoverflow.com/questions/13562635/deserialize-xml-object-in-t-sql) – Rajesh 2014-09-26 07:59:45

回答

1

假設SqlXml對象包含問題中提到的確切內容,您可能需要使用以下輔助方法。應該適用於以這種方式序列化的任何類型,即使是複雜的對象。

static T GetValue<T>(SqlXml sqlXml) 
{ 
    T value; 

    // using System.Xml; 
    using (XmlReader xmlReader = sqlXml.CreateReader()) 
    { 
     // using System.Xml.Serialization; 
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); 
     value = (T) xmlSerializer.Deserialize(xmlReader); 
    } 

    return value; 
} 

實施例的情況下:

using (MemoryStream stream = new MemoryStream()) 
using (XmlWriter writer = new XmlTextWriter(stream, Encoding.ASCII)) 
{ 
    writer.WriteRaw("<int>123</int>"); 
    writer.Flush(); 

    stream.Seek(0, SeekOrigin.Begin); 

    using (XmlReader reader = new XmlTextReader(stream)) 
    { 
     SqlXml sqlXml = new SqlXml(reader); 

     int value = GetValue<Int32>(sqlXml); 

     Debug.Assert(123 == value); 
    } 
}