2012-12-18 50 views
0

我在數據類型爲XML的SQL Server數據庫表中有一個字段。使用ASP.NET(C#)在SQL Server中插入和選擇XML數據

建議的格式如下:

<remarks> 
    <remark> 
     <author>Patrick Keane</author> 
     <date>18/12/2012 10:06</date> 
     <content>My content Here</content> 
    </remark> 
    <remark> 
     <author>Joe Blogs</author> 
     <date>19/12/2012 11:32</date> 
     <content>My content Here</content> 
    </remark> 
    ...... 
    ...... 
</remarks> 

使用ASP.NET(C#),我想添加一個新進入這個領域(這可能會或可能不會已經在它的條目)。 我也希望能夠檢索最後一個條目(用於在.aspx頁面上顯示)和條目的完整列表(用於在.xml頁面上顯示)。

我一直在尋找信息/教程,我發現大多數是導出數據和轉換爲XML。任何人都可以指向我的相關教程或爲我提供一些信息?泰

回答

0

要插入:

傳遞你想在存儲過程中追加作爲參數,然後嘗試以下查詢XML:

update [dbo].[TableName] 
    set remark.modify ('insert sql:variable("@varibleName") as last into (/remarks/)[1]') WHERE [Condition] 
0

您可以使用抱你贏得了數據的類導出(並導入)到XML。
您可以使用[Serializable]使該類可用於xml導出。因此,舉例來說,如果你有這個類:

[Serializable] 
public class MyClassThatKeepTheData 
{ 
    public List<int> cListWithValues; 

    public int Value1; 

    public int Value2; 
} 

然後你可以使用XmlSerializer將其轉換爲XML(和反之亦然)爲:

public static string ObjectToXML(Type type, object obby) 
{ 
    XmlSerializer ser = new XmlSerializer(type); 
    using (System.IO.MemoryStream stm = new System.IO.MemoryStream()) 
    { 
     //serialize to a memory stream 
     ser.Serialize(stm, obby); 
     //reset to beginning so we can read it. 
     stm.Position = 0; 
     //Convert a string. 
     using (System.IO.StreamReader stmReader = new System.IO.StreamReader(stm)) 
     { 
      string xmlData = stmReader.ReadToEnd(); 
      return xmlData; 
     } 
    } 
} 

public static object XmlToObject(Type type, string xml) 
{ 
    object oOut = null;  

    if (xml != null && xml.Length > 0) 
    { 
     System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type); 

     using (System.IO.StringReader sReader = new System.IO.StringReader(xml)) 
     { 
      oOut = serializer.Deserialize(sReader); 

      sReader.Close(); 
     } 
    } 

    return oOut; 
} 

,並轉換爲XML:

MyClassThatKeepTheData cTheObject = new MyClassThatKeepTheData(); 

ObjectToXML(typeof(MyClassThatKeepTheData), cTheObject) 

相對: How to optimize class for viewstate

我建議也日e protobuf-net不是XML,但它快很多,並且做同樣的工作

相關問題