2013-08-19 543 views
0

我有下面的XML:集元素XML屬性值的LINQ

<appsettings> 

    <add key="MDXQueryDirectory" value="" /> 

    <add key="URLPrefix" value="/Manager" /> 

</appsettings> 

和代碼:

XElement doc = XElement.Load(@"config_path"); 


var element = doc.Elements("add") 
      .SingleOrDefault(x => x.Attribute("key").Value == "MDXQueryDirectory"); 


element.SetAttributeValue("value", txtMDXQueryDirectory.Text); 

我想將txtMDXQueryDirectory文本數據分配給MDXQueryDirectory appSsetting。首先我使用Single方法,但它不工作,我研究谷歌我發現這page所以錯誤解決相關的文章。但知道SingleOrDefault方法不起作用。它拋出NullPointerException (Object reference not set to an instance an object)

我該如何解決問題,或者你可能會建議不同的習語在xml中設置數值數據?

+0

「doc」或「doc.Elements(」add「)」或「x.Attribute(」key「)」對象是否爲空?你檢查過了嗎? –

+0

大的可能性Lİnq查詢沒有找到正確的xml節點。以下代碼示例提供了您的問題答案。但代碼仍然無法正常工作。 –

+0

請檢查我提到的所有3件事情,看看究竟是什麼原因造成的異常。到目前爲止,您沒有任何安全檢查。 –

回答

4

你需要改變,你要選擇的更新元素的查詢,它應該是:

XDocument doc = XDocument.Load(@"config_path"); 

var element = doc.Descendants().Elements("add") 
       .SingleOrDefault(x => x.Attribute("key").Value == "MDXQueryDirectory"); 

element.SetAttributeValue("value", txtMDXQueryDirectory.Text); 

doc.Save(@"config_path"); 

獲取文件時,也應使用XDocument而非XElement

注意:XDocument.Load(@"config_path") - 應指向您的XML文件的位置。目前它不。

+0

它不工作在我身邊仍然我得到「System.NullReferenceException:對象引用未設置爲對象的實例。」 –

+0

今年秋天會發生什麼?如果你的XML與你的OP中發佈的相同,那麼這個錯誤是在你的代碼中的其他地方,因爲我已經在本地進行了測試,並且沒問題。 – DGibbs

+0

這裏不需要XDocument。很少有。 –

0
string config_file = @"config_file_path"; 

var element = doc.Element("appSettings").Elements("add") 
          .SingleOrDefault(x => x.Attribute("key").Value.ToString() == "MDXQueryDirectory"); 

element.SetAttributeValue("value", txtMDXQueryDirectory.Text); 
doc.Save(@"config_file_path"); 

此代碼塊工作正常。我認爲這個問題與我身邊的xml節點有關。感謝所有回覆。

相關問題