在 C# 中创建一个新的 xmlElement

Create a New xmlElement in c#

嗨,我有一个问题,我有这个 XML 文件作为我的配置文件

<?xml version="1.0" encoding="utf-8"?>
 <configs>
   <config>
     <starmade_path>null</starmade_path>
     <gui_path>null</gui_path>
     <first_start>true</first_start>
     <dark_theme>false</dark_theme>
     <light_theme>true</light_theme>
     <OSM_theme>false</OSM_theme>
   </config>
 </configs>

如果文件中不存在新元素,我需要先添加它,这样我的 XML 文件看起来像这样

<?xml version="1.0" encoding="utf-8"?>
 <configs>
   <config>
    <starmade_path>null</starmade_path>
    <gui_path>null</gui_path>
    <first_start>true</first_start>
    <dark_theme>false</dark_theme>
    <light_theme>true</light_theme>
    <OSM_theme>false</OSM_theme>
    <Red_theme>sampleText</Red_theme>
  </config>
</configs>

使用此代码,此代码添加 starmade_path 如果不存在,这样您也可以检查并添加其他节点

            XDocument doc = XDocument.Load(@"D:\a.XML");
            XElement root = doc.Element("configs");
            XElement config = root.Element("config");
            XElement starmade_path = config.Element("starmade_path");

            if (starmade_path == null)
            {
                XElement n = new XElement("starmade_path");
                n.Value = "aljd";
                config.Add(n);
                doc.Save(@"D:\a.XML");
            }

试试这个。如果 xelement 中不存在,它将添加 Red_theme。

 XDocument xml = XDocument.Load("yourfile");
        XElement configelement= xml.Descendants("config").First();
        XElement element = configelement.Elements().FirstOrDefault(x => x.Name== "Red_theme");
        if (element == null)
        {
            element = new XElement("Red_theme");
            element.Value = "sampletext";
            configelement.Add(element);        
        }