Search code examples
c#xmlxelement

Change Xml value with XElement (with specified Attributes)


<?xml version="1.0" encoding="utf-8"?>
<Instances>
  <InstanceInfos Name="i-82c61ac1">
    <MaxTime>38</MaxTime>
  </InstanceInfos>
  <InstanceInfos Name="i-83c61ac0">
    <MaxTime>447</MaxTime>
  </InstanceInfos>
</Instances>

Hello, I am looking a way to edit a specified value with Xelement by specify the attribute (ex: i-82c61ac1).

(Actually i know how to load xml file and add Elements, but i am stuck for editing value specified by Attributs.)

for exemple i want to edit <MaxTime>38</MaxTime> but only under <InstanceInfos Name="i-82c61ac1">

Thank for your help,

Best regards.


Solution

  • XDocument xDoc = XDocument.Load("file.xml");
    
            XElement result = xDoc.Descendants("InstanceInfos")
                .Where(x => x.Attribute("Name")
                    .Value == "i-82c61ac1")
                .Descendants()
                .SingleOrDefault();
    
            result.Value = "Foo";
    
            xDoc.Save("file.xml");