XML 文件更改内容

本文关键字:文件 XML | 更新日期: 2023-09-27 18:30:27

首先,答案可能很简单,但是我已经尝试了许多看似正常的解决方案,无论我尝试什么,都没有让它们工作。

我得到了这个XML文件:

<?xml version="1.0" encoding="utf-8"?>
    <Config>
      <PopulationSize>100</PopulationSize>
      <SpecieCount>20</SpecieCount>
      <Activation>
        <Scheme>FixedIters</Scheme>
        <Iters>1</Iters>
      </Activation>
      <ComplexityRegulationStrategy>Absolute</ComplexityRegulationStrategy>
      <ComplexityThreshold>500</ComplexityThreshold>
      <Description>
        Helikopter game
      </Description>
      <Timesteps>50000</Timesteps> //Length of the world (x-axis)
      <Worldheight>200</Worldheight> //Height of the world (y-axis)
      <SensorInputs>10</SensorInputs> //Length of one side of the rectangle that is used as the input. So 15 here means 15*15 = 225 inputs
      <Speler>computer</Speler>
    </Config>

我想编辑

    <Speler>computer</Speler>

到类似的东西

    <Speler>mens</Speler>

目前,我想要一些类似的东西:

        XmlDocument doc = new XmlDocument();
        doc.Load("Helikopter.config.xml");
        //Change the contents of "Speler" to "Mens"
        doc.Save("Helikopter.config.xml");

但我似乎无法让它工作,无论我尝试放在那里什么,我已经在这里尝试了很多选择。

帮助是肯定的,谢谢

XML 文件更改内容

这样的事情怎么样:

XmlDocument doc = new XmlDocument();
doc.Load("Helikopter.config.xml");
XmlNode node;
node = doc.DocumentElement;
// Iterate through all nodes
foreach(XmlNode node1 in doc.ChildNodes)
{
    // if the node is speler
    if(node1.Name == "speler")
    {
        // Change inner text to mens
        node1.InnerText = "mens";
    }
}
doc.Save("Helikopter.config.xml");
    static void Main(string[] args)
    {
        string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Config>
  <PopulationSize>100</PopulationSize>
  <SpecieCount>20</SpecieCount>
  <Activation>
    <Scheme>FixedIters</Scheme>
    <Iters>1</Iters>
  </Activation>
  <ComplexityRegulationStrategy>Absolute</ComplexityRegulationStrategy>
  <ComplexityThreshold>500</ComplexityThreshold>
  <Description>
    Helikopter game
  </Description>
  <Timesteps>50000</Timesteps> //Length of the world (x-axis)
  <Worldheight>200</Worldheight> //Height of the world (y-axis)
  <SensorInputs>10</SensorInputs> //Length of one side of the rectangle that is used as the input. So 15 here means 15*15 = 225 inputs
  <Speler>computer</Speler>
</Config>";
        XDocument doc = XDocument.Parse(xml);
        List<XElement> elements = doc.Descendants("Config").ToList();
        foreach (XElement elem in elements)
        {
            elem.Element("Speler").Value = "mens";
            Console.WriteLine(elem.Element("Speler").Value);
        }
        Console.ReadKey();
    }

这里有一个如何做到这一点的例子。您需要参考使用System.Xml.Linq;