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:You might find it easier using Linq to XML for updating your XML going forward –
XmlDocumentis not very easy to use.Also your current XML is not valid – let’s assume it looks like this:
Then you can increment your id’s using Linq to XML like this: