简体   繁体   中英

I want to update my xml column in the database using C#

Hi All Is been while since I am trying to figuare out how to update my xml Column in my SQLServer Table. Ok for clear understanding I want to increment each and every id by 1. Ok this is my Tablename called Setting(SettingId int pk, Name nVarchar(100), XmlSetting xml)

//my data.xml

<setting>
<a id=1/>
<b id=2/>
<c id=22>
</setting>

My C# code for Incrementing this code is below

XmlDocument xdoc = new XmlDocument();


private void SetAttribute(System.Xml.XmlNode node)//this code is running in the memory
  {

     System.Xml.XmlElement element = node as System.Xml.XmlElement;

      if (element != null)
            {
                int attributeCount = element.Attributes.Count;

                for (int i = 0; i < attributeCount; i++)
                {
                    System.Xml.XmlAttribute attribute = element.Attributes[i];

       if (string.Compare(attribute.Name, "Id", System.StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        int value;
                        if (int.TryParse(attribute.Value, out value))
                        {
                            attribute.Value = (value + 1).ToString();
                        }
                        else
                        {
                            attribute.Value = "1";
                        }
                    }
                }
                int childNodeCount = element.ChildNodes.Count;
                for (int i = 0; i < childNodeCount; i++)
                {
                    SetAttribute(element.ChildNodes[i]);
                }
            }
        }
        public void EditXmlFile()
        {
            xdoc.Load(FILE_NAME);
            SetAttribute(xdoc.FirstChild);
            return;
        }

All what I am asking for is to update this code into my Database table Setting

private void btnUpdate_Click(object sender, EventArgs e)
{

SqlConnection cnn = new SqlConnection("connectionPath");

SqlCommand cmd=new SqlCommand("Update Setting set SettingXml=@Settingxml where settingId=5",cnn);
cmd.Parameters.AddWithValue("@SettingXml","")//this where I am stacked because I am failing
        try
        {
           cnn.Open();
           cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {

            lblmsg.Text = "Error updating Xml " + ex.Message;
        }

}

How can update I update this SettingXml column with the above function because I want to increment every id by 1

You have to pass the updated XML as a string to your SqlParameter , so something like this:

SqlCommand cmd=new SqlCommand("Update Setting set SettingXml=@SettingXml where settingId=5",cnn);
cmd.Parameters.Add(new SqlParameter("@SettingXml", SqlDbType.Xml)).Value = xdoc.OuterXml;

You might find it easier using Linq to XML for updating your XML going forward - XmlDocument is not very easy to use.

Also your current XML is not valid - let's assume it looks like this:

<setting>
  <a id="1"/>
  <b id="2"/>
  <c id="22"/>
</setting>

Then you can increment your id's using Linq to XML like this:

XDocument doc = XDocument.Load("test.xml");
doc.Root
   .Elements()
   .ToList()
   .ForEach(node => node.Attribute("id").Value = (Convert.ToInt32(node.Attribute("id").Value) + 1).ToString());

string xml = doc.ToString();

This would be so much easier if you used LINQ. As @BrokenGlass pointed out the Linq to XML makes updating the XML much cleaner, and Linq to SQL will make your database update much cleaner also. It should look something like this.

var dbContext = new MyDbContext();
dbContext.Settings.First(s => s.id == 5).XmlSetting = doc.Elements().First();
dbContext.SubmitChanges();

You should really spend some time learning Linq as it will make things like this so simple.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM