开发者

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开发者_如何学Go" 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");


Is there any reason why answers provided by these guys wont write to XML? There is no exception, everything looks fine except it does not write to file.

Here's mine code

string file = "c:/message.xml";
XDocument d = XDocument.Load(file);

SetValueToIdElement(d, id, value);

private static void SetValueToIdElement(XDocument doc, string Id, string value)
        {
            var detail = doc.Elements("context").SingleOrDefault(x => x.Attribute("id").Value == Id);
            if (detail != null)
                detail.SetAttributeValue("value", value);
        }

Basically it is same as above

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜