-2
<?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.

Romeh
  • 29
  • 8
  • 2
    Hint: use `Descendants` or `Elements` to find all the elements with the right names, and then `Where` to select elements with the right attribute values. – Jon Skeet Jun 10 '14 at 11:29

2 Answers2

1
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");
Daniel Dutton
  • 187
  • 1
  • 15
0

You can use XDocument to load the xml and use Descendants

    private static void Main(string[] args)
    {
        var data = @"<?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>";
        var document = XDocument.Parse(data);
        const string attributeId = "i-82c61ac1";
        var element = document.Descendants("InstanceInfos").FirstOrDefault(p => p.Attribute("Name").Value.Equals(attributeId));
        if (element != null)
        {
            var maxTime = element.Elements("MaxTime").FirstOrDefault();
            if (maxTime != null) maxTime.Value = "100";
        }
        document.Save("FinalResult.xml");
    }
cvraman
  • 1,687
  • 1
  • 12
  • 18