Update the Attribute value using LINQ
Here i would like to show you, how to Query the XML using LINQ and Update the attribute value for one of the Element.
Here i am using LINQ to load the XML and Query the XML to get the element based on its attribute value. Getting the child element we will update the value of attribute for one of the child element.
Here i am using LINQ to load the XML and Query the XML to get the element based on its attribute value. Getting the child element we will update the value of attribute for one of the child element.
1. I am Loading the XML String not the XML file. XML looks like some thing. We can also save the XML and Load the XML instead of XML String. Just for simplicity and for better understanding, i am using XML String.
string str = @"<Questions><Questionary ID='29'>" +
"<Question>Sharepoint 2010</Question>" +
"<Option1 Correct='No'>option1</Option1>" +
"<Option2 Correct='No'>option2</Option2>" +
"<Option3 Correct='Yes'>option3</Option3>" +
"<Option4 Correct='No'>option4</Option4>" +
"<Type>Optional<Type>" +
"</Questionary>" +
"<Questionary ID='28'>" +
"<Question>Silverlight 4</Question>" +
"<Option1 Correct='No'>option1</Option1> " +
"<Option2 Correct='No'>option2</Option2> " +
"<Option3 Correct='Yes'>option3</Option3> " +
"<Option4 Correct='No'>option4</Option4> " +
"<Type>Optional</Type> " +
"</Questionary></Questions>
Now using LINQ to XML Concept we can load the XML String, We can do that in two ways,
1. using XElement Class to load the xml string.
XElement element = XElement.Parse(str);
or if you have XML file then you can use
XElement element = XElement.load("fileName");
After parsing or loading the XML we can query the XML. Here i am query the xml based on the Atribute i.e. 29 and get the Element.
After getting Element will UPDATE attribute value of the OPTION1.
class Program
{
static void Main(string[] args)
{
updateXMLAttrib();
}
static void updateXMLAttrib()
{
string str = @"<Questions><Questionary ID='29'>" +
"<Question>Sharepoint 2010</Question>" +
"<Option1 Correct='No'>option1</Option1>" +
"<Option2 Correct='No'>option2</Option2>" +
"<Option3 Correct='Yes'>option3</Option3>" +
"<Option4 Correct='No'>option4</Option4>" +
"<Type>Optional<Type>" +
"</Questionary>" +
"<Questionary ID='28'>" +
"<Question>Silverlight 4</Question>" +
"<Option1 Correct='No'>option1</Option1> " +
"<Option2 Correct='No'>option2</Option2> " +
"<Option3 Correct='Yes'>option3</Option3> " +
"<Option4 Correct='No'>option4</Option4> " +
"<Type>Optional</Type> " +
"</Questionary></Questions>
XElement element = XElement.Parse(str);
var p = from c in XElement.Parse(str).Elements("Questionary")
where (string)c.Attribute("ID") == "29"
select c;
((IEnumerable
Console.WriteLine(p.ToList
Console.Read();
}
}
Thanks