2017-03-14 126 views
0

我對C#比較陌生,剛開始使用XmlElement和SingleNode方法。出於某種原因,「customSettings」保持返回null,儘管正在加載XML文檔。我已經通過加載它作爲一個字符串來檢查。我已經嘗試了迄今爲止我能想象到的一切,包括評論中的嘗試。任何幫助或建議非常感謝。這是我的XML文檔:C#XmlElement:爲什麼總是返回Nulll?

編輯:從CodingYoshi解決方案,但有沒有更好的方法?

編輯:改變XML和代碼NSGaga解決user.config與NameValueCollection中讀取唯一的例外

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
    <section name="users_fächer" type="System.Configuration.NameValueSectionHandler" /> 
    </configSections> 
    <users_faecher> 
    <add key="user1" value="value1" /> 
    <add key="user2" value="value2" /> 
    </users_faecher> 
</configuration> 

代碼:

string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Users.config"); 
string new_fächer = input[1]; 
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap(); 
configMap.ExeConfigFilename = dir; 
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); 

ConfigurationSection myParamsSection = config.GetSection("users_faecher"); 

string myParamsSectionRawXml = myParamsSection.SectionInformation.GetRawXml(); 
XmlDocument sectionXmlDoc = new XmlDocument(); 
sectionXmlDoc.Load(new StringReader(myParamsSectionRawXml)); 
NameValueSectionHandler handler = new NameValueSectionHandler(); 

NameValueCollection users_fächer = handler.Create(null, null, sectionXmlDoc.DocumentElement) as NameValueCollection; 

users_fächer.Set(user, new_fächer); 
config.Save(ConfigurationSaveMode.Modified, true); 
+0

尼古拉你可以發佈一個小控制檯項目 - 'VAR customSettings = ConfigurationManager.GetSection( 「數據/ faecher」)作爲NameValueCollection中;'不應該返回null,一切是正確的存在。而且你不應該像XML那樣加載配置文件,因爲它非常糟糕:)。這裏還有其他一些問題,我只是不確定你在做什麼。因此,剝離所有其他東西只是配置,因爲你有它,並且一行 – NSGaga

+0

@NSGaga發現打開該部分的問題,但是當我嘗試在NameValueCollection上設置方法它告訴我它的只讀,雖然它的自定義用戶.config而不是一個app.config。我編輯了代碼和xml數據讓你看到我現在得到了什麼 – Nikolas

+0

@NSGaga現在都編輯了,你有什麼線索爲什麼它不讓我編輯? – Nikolas

回答

1

這將讓你第一add元素:

doc.ChildNodes[0].NextSibling.ChildNodes[1].ChildNodes[0].ChildNodes[0]; 

這會給你第一個add elem ent的value屬性。

doc.ChildNodes[0].NextSibling.ChildNodes[1] 
    .ChildNodes[0].ChildNodes[0].Attributes["value"].Value; 
+0

雖然這是現在的工作,這是真棒,你有任何想法如何解決以前或修改你的,不必循環所有的孩子找到一個具有正確的關鍵屬性? – Nikolas

+0

爲什麼你在乎循環尋找你需要的目標元素?如果你擔心表現:你多久會這樣做?這是否成爲瓶頸? – CodingYoshi

相關問題