Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Attribute value in LINQ to XML

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.

like image 329
Mohit Kumar Avatar asked Aug 31 '11 17:08

Mohit Kumar


2 Answers

You can use the XElement.SetAttributeValue() method:

var element = doc.Elements("Details")
                 .Single(x=>x.Attribute("XIndex").Value=="One");

element.SetAttributeValue("Index", "First");
like image 121
Mark Cidade Avatar answered Nov 14 '22 10:11

Mark Cidade


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");
like image 40
arviman Avatar answered Nov 14 '22 10:11

arviman