2012-07-26 77 views
0

我想知道如何將XDocument的特定部分寫入文件。C#LINQ to XML - 如何將特定的XElements寫入文件

假設我在應用程序啓動時加載整個文檔,然後使用應用程序加載讀取設置。當我修改我的類的屬性,我希望寫只是財產(或僅僅是屬性及其子女)迴文件,留下不變的任何其他修改到的XDocument(在內存中)

我現在代碼如下所示(請注意我周圍的XDocument和的XElement類的一些包裝):

public void SaveRecursiveData() 
    { 
     //Load the original file into a new document 
     XmlConfig tmp = new XmlConfig(_XmlDoc.Filename,false); 

     //find the node i am interested in 
     XElement currentElement = tmp.Xmldoc.XPathSelectElement(this.Path); 

     //Replace it with my IN MEMORY one 
     currentElement.ReplaceWith(_XmlNode); 

     //Write the whole temporary document back to the file 
     tmp.Save(); 
    } 

這是最好的辦法還是有另一種方式?

+0

你做一些研究,你在這裏張貼問題之前? 3-rd link in fraze'xml linq tutorial' is'http:// www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial /' – harry180 2012-07-26 08:53:13

+0

是的,我已經做了一些研究,不幸的是,你提供的鏈接並不能解決我的問題。這裏的關鍵是「在內存中不改變對XDocument的任何其他修改」 – Simon 2012-07-26 08:57:24

回答

-1

你可以做

currentElement.Attribute("toChange").Value = "mynewvalue"; 

,而不是ReplaceWith