C# XML 文件:如何使用 LINQ select 具有特定值的节点

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

我很难找出 Linq 方法来提取特定节点的值。

假设我的 XML 文件是这样的:

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

我想从 Count 中提取值,它来自 ToolTool_Name 的值为 OffMonth 其中 Month_Number3.

答案应该是1。然后我想将该值更改为 2

因此生成的 XML 文件将是

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

使用 XML文档 我会做类似于

的事情
XmlDocument tallyFile = new XmlDocument();
                    tallyFile.Load(tallyFilePath);

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

但我想使用 XDocument

来实现上述目的

你能试试这个代码吗,只参考 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";
}