C# XML File: How to select a node with a certain value using LINQ

Viewed 59

I am having difficulties figuring out the Linq way to extract the value of the specific node.

Lets say my XML file is this:

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <Month>
    <Month_Number>1</Month_Number>
    <Tool>
      <Tool_Name>Help</Tool_Name>
      <Count>1</Count>
    </Tool>
  </Month>
  <Month>
    <Month_Number>2</Month_Number>
    <Tool>
      <Tool_Name>On</Tool_Name>
      <Count>1</Count>
    </Tool>
  </Month>
  <Month>
    <Month_Number>3</Month_Number>
    <Tool>
      <Tool_Name>Off</Tool_Name>
      <Count>1</Count>
    </Tool>
  </Month>
</Data>

I would like to extract value fromCount which is from Tool with Tool_Name with value of Off in Month where Month_Number is 3.

The answer should be 1. Then I would like to change that value to 2

So resulting XML file would be

<?xml version="1.0" encoding="utf-8"?>
<Data>
  <Month>
    <Month_Number>1</Month_Number>
    <Tool>
      <Tool_Name>Help</Tool_Name>
      <Count>1</Count>
    </Tool>
  </Month>
  <Month>
    <Month_Number>2</Month_Number>
    <Tool>
      <Tool_Name>On</Tool_Name>
      <Count>1</Count>
    </Tool>
  </Month>
  <Month>
    <Month_Number>3</Month_Number>
    <Tool>
      <Tool_Name>Off</Tool_Name>
      <Count>2</Count>
    </Tool>
  </Month>
</Data>

using XMLDocument I would do something similar to

XmlDocument tallyFile = new XmlDocument();
                    tallyFile.Load(tallyFilePath);

                    XmlNode node = tallyFile["Data"];
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode["Month_Number"].InnerText.Equals("3")){}
}

But I would like to achieve the above using XDocument

1 Answers

Can you try this code, just reference the docs

using System.Xml.Linq;

XElement root = XElement.Load(tallyFilePath);
foreach (var month in root.Descendants("Month")
    .Where(x => x.Descendants("Month_Number").First().Value == "3"))
{
    Console.WriteLine(month);
    //month.Value = "2";
}
Related