簡體   English   中英

使用ASP.NET(C#)在SQL Server中插入和選擇XML數據

[英]Inserting and Selecting XML data in SQL Server with ASP.NET (C#)

我在數據類型為XML的SQL Server數據庫表中有一個字段。

提議的格式如下:

<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。 誰能給我指出相關的教程或為我提供一些信息?

要插入:

將要附加到存儲過程中的xml作為參數傳遞,然后嘗試以下查詢:

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

您可以使用一個類來保存將導出(和導入)到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)

相對: 如何為viewstate優化類

而且我建議protobuf-net不是XML,但是它的速度要快得多,並且可以完成相同的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM