XML文件更改内容

时间:2016-01-14 14:43:19

标签: c# xml

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

我有这个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");

但我似乎无法让它发挥作用,无论我试图放在那里,我已经在这里尝试了很多选择。

帮助很好,谢谢

2 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

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");

答案 1 :(得分:0)

    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;