John
John

Reputation: 971

Update xml values based on an attributes value using c#

Im trying to use c# to update an xml file. If a machine name is 'MachineName3' then update the value to be '122.0.6261.112'

<?xml version="1.0" encoding="utf-8"?>
<Variables>
  <Variable name="MachineName1" application="chrome">122.0.6261.112</Variable>
  <Variable name="MachineName2" application="chrome">122.0.6261.112</Variable>
  <Variable name="MachineName3" application="chrome">122.0.6260.109</Variable>
  <Variable name="MachineName4" application="chrome">122.0.6261.110</Variable>
</Variables>

But my code below updates MachineName1.

XDocument xdoc = XDocument.Load(variablesFile);
var allElements = xdoc.Descendants();
foreach (XElement element in allElements)
{
    if (xdoc.Root.Descendants("Variable").FirstOrDefault().HasAttributes.Equals("MachineName3"));
       
    {
        xdoc.Root.Descendants("Variable").FirstOrDefault().SetValue("122.0.6261.112");
    }
}

Any help is much appreciated.

Upvotes: 0

Views: 39

Answers (1)

Dai
Dai

Reputation: 154995

You only need a single XDocument.Descendants(...).Where(...).Single() to get the <Variable name="MachineName3" ...> element, then re-set its .Value and re-save the XDocument, like so:

XDocument xdoc = XDocument.Load( variablesFile );

XElement machine3VariableEl = xdoc.Descendants( "Variable" )
    .Where( e => e.Attribute( "name" )?.Value == "MachineName3" )
    .Single();

machine3VariableEl.Value = "122.0.6261.112";

xdoc.Save( fileName: variablesFile + ".modified.xml" );

Upvotes: 1

Related Questions