C# How Can I Replace Two Xml Element Values?

69 views Asked by At

Starter Code:

var xDocument = XDocument.Parse(rawXmlString);

Imagine that I've loaded the XML below in an XDocument and I'd like to use Linq-to-XML:

<ParameterValues>
    <ParameterValue>
        <Name>Head Coach</Name>
        <Value>Bill Belichick</Value>
    </ParameterValue>
    <ParameterValue>
        <Name>Quarterback</Name>
        <Value>Mac Jones</Value>
    </ParameterValue>
</ParameterValues>

With C#, keying off of the Name values Head Coach and Quarterback respectively, how can I replace:

  • Bill Belichick with Mike Vrabel?
  • Mac Jones with Kirk Cousins?

  • Also, if it helps, this XML document will exist in memory only. It will not be persisted to a file.
  • ParameterValues will indeed be the root node.
  • The ParameterValue nodes may be out of order and someday there may be more than two subnodes.

What I've tried:

var xDocument = XDocument.Parse(rawXmlString);

I've experimented with various Linq-to-XML query methods but without much luck so far.

1

There are 1 answers

0
Yitzhak Khabinsky On BEST ANSWER

Here it is via LINQ to XML.

c#

void Main()
{
    const string NEWHEADCOACH = "Mike Vrabel";
    const string NEWQUARTERBACK = "Kirk Cousins";

    XDocument xdoc = XDocument.Parse(@"<ParameterValues>
            <ParameterValue>
                <Name>Head Coach</Name>
                <Value>Bill Belichick</Value>
            </ParameterValue>
            <ParameterValue>
                <Name>Quarterback</Name>
                <Value>Mac Jones</Value>
            </ParameterValue>
        </ParameterValues>");
        
    xdoc.Descendants("ParameterValue")
        .Where(x => x.Element("Name").Value == "Head Coach")
        .Elements("Value").FirstOrDefault()?.SetValue(NEWHEADCOACH);

    xdoc.Descendants("ParameterValue")
        .Where(x => x.Element("Name").Value == "Quarterback")
        .Elements("Value").FirstOrDefault()?.SetValue(NEWQUARTERBACK);

    Console.WriteLine(xdoc);
}

Output

<ParameterValues>
  <ParameterValue>
    <Name>Head Coach</Name>
    <Value>Mike Vrabel</Value>
  </ParameterValue>
  <ParameterValue>
    <Name>Quarterback</Name>
    <Value>Kirk Cousins</Value>
  </ParameterValue>
</ParameterValues>