2016-05-15 136 views
0

嗨,我有一個問題我有這樣的XML文件作爲我的配置文件在C#中創建一個新的XmlElement

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

如果它doesent文件中存在,所以我的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> 

回答

0

使用此代碼,該代碼添加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"); 
      } 
+0

謝謝,它完美^^ – Agronaut022

+0

你是惠康 – Mostafiz

0

試試這個。如果不存在於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);   
     } 
+0

作品太感謝了藏漢^^ – Agronaut022

+0

我相信@ agronaut022做到了。乾杯。 – riteshmeher