I am newbie in LINQ to XML.I have two variable one and two and I want to set these variable values in attribute in XML.
 static void Main(string[] args)
    {
        string one = "first";
        string two = "Second";
        XDocument doc = XDocument.Load(test.xml);
    }
XML
    <Root>
  <Details XIndex="One" Index="">
    <abc></abc>
  </Details>
  <Details XIndex="Two" Index="">
    <xyz></xyz>
  </Details>
</Root>
Now please tell me how I can set One and two variables value in Index attribute in details node.
Example - I want below output.
<Root>
  <Details XIndex="One" Index="First">
    <abc></abc>
  </Details>
  <Details XIndex="Two" Index="Second">
    <xyz></xyz>
  </Details>
</Root>
Please tell me.
Thanks in advance.
You can use the XElement.SetAttributeValue() method:
var element = doc.Elements("Details")
                 .Single(x=>x.Attribute("XIndex").Value=="One");
element.SetAttributeValue("Index", "First");
                        If you're going to be making this call often, you might as well put it into a helper method such as:
private static void SetValueToDetailElement(XDocument doc, string xIndex, string value)
{
  var detail = doc.Elements("Details").SingleOrDefault(x=>x.Attribute("XIndex").Value==xIndex);
  if(detail != null)
     detail.SetAttributeValue("Index", value);
}
and then call the following in your main.
SetValueToDetailElement(doc, "One", "First");
SetValueToDetailElement(doc, "Two", "Second");
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With