C#XML读取和编辑子值

时间:2018-08-15 19:26:24

标签: c# xml

编辑

问题解决了,对于那些需要它的人,这就是我所做的

编辑的XML:

<?xml version="1.0" encoding="utf-8" ?>
<!-- DON'T EDIT THIS FILE!-->
<config>
  <DirectoryIndex value="False" />
  <FirstRun value="True" />
  <GamePath value="" />
  <Language value="English" />
</config>

从XML获取值:

var XMLDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "config.xml");

string DirectoryIndex = XMLDoc.Root.Element(XName.Get("DirectoryIndex")).Attribute("value").Value;
string GamePath = XMLDoc.Root.Element(XName.Get("GamePath")).Attribute("value").Value;
string Language = XMLDoc.Root.Element(XName.Get("Language")).Attribute("value").Value;
string FirstRun = XMLDoc.Root.Element(XName.Get("FirstRun")).Attribute("value").Value;

编辑并保存值:

XMLDoc.Root.Element(XName.Get("DirectoryIndex")).Attribute("value").SetValue("NewValue");
XMLDoc.Root.Element(XName.Get("GamePath")).Attribute("value").SetValue("NewValue");
XMLDoc.Root.Element(XName.Get("Language")).Attribute("value").SetValue("NewValue");
XMLDoc.Root.Element(XName.Get("FirstRun")).Attribute("value").SetValue("NewValue");

XMLDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "config.xml");

  

我有这个XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<!-- DON'T EDIT THIS FILE!-->
<config>
  <setting key="DirectoryIndex">
    <value>False</value>
  </setting>
  <setting key="GamePath">
    <value></value>
  </setting>
  <setting key="Language">
    <value>English</value>
  </setting>
  <setting key="FirstRun">
    <value>True</value>
  </setting>
</config>
     

我的应用程序需要在字符串变量中分配来自   XML文件。示例:

string DirectoryIndex = "Instructions To Get "DirectoryIndex" value from XML file";
string GamePath = "Instructions To Get "GamePath" value from XML file";
string Language = "Instructions To Get "Language" value from XML file";
string FirstRun= "Instructions To Get "FirstRun" value from XML file";
     

接下来,在分配所有变量后,我需要在其中编辑值   XML文件。示例:

string NewValueForDirectoryIndex = "True";
     

我想要这个输出:

<setting key="DirectoryIndex">
  <value>True</value> <!-- Obtained from "NewValueForDirectoryIndex" -->

0 个答案:

没有答案