2009-01-27 208 views
3

讀取XML文件並獲取確切的節點文本非常容易,但是如何使用新值更新該節點?如何更新XML節點?

閱讀:

public static String GetSettings(SettingsType type, SectionType section) 
{ 
    XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); 
    XmlDocument document = new XmlDocument(); 
    document.Load(reader); 

    XmlNode node = document.SelectSingleNode(
         String.Format("/MyRootName/MySubNode/{0}/{1}", 
         Enum.Parse(typeof(SettingsType), type.ToString()), 
         Enum.Parse(typeof(SectionType), section.ToString())));  
    return node.InnerText; 
} 

寫的......?

public static void SetSettings(SettingsType type, SectionType section, String value) 
{ 
    try 
    { 
     XmlTextReader reader = new XmlTextReader(HttpContext.Current.Request.MapPath(APPSETTINGSPATH)); 
     XmlDocument document = new XmlDocument(); 
     document.Load(reader); 

     XmlNode node = document.SelectSingleNode(
          String.Format("/MyRootName/MySubNode/{0}/{1}", 
          Enum.Parse(typeof(SettingsType), type.ToString()), 
          Enum.Parse(typeof(SectionType), section.ToString()))); 
     node.InnerText = value; 
     node.Update(); 
    } 
    catch (Exception ex) 
    { 
     throw new Exception("Error:", ex); 
    } 
} 

行,node.Update();不存在,但這就是我想要的:)

我看到了XmlTextWriter對象,但它會將整個XML寫入一個新文件,並且我只需要在原始Node中更新一個值,我可以另存爲一個新的文件,然後將新文件重命名爲原始名稱,但是......它必須更簡單才能做到這一點?

你們中的任何一個人都有一個示例代碼即將做到這一點?

謝謝

回答

8

您不需要「更新」方法 - 設置InnerText屬性更新它。但是,它僅在內存中應用更新。你雖然需要重寫整個文件 - 你不能只更新它的一小部分(至少,沒有lot的工作,沒有開箱即用的支持)。

3

XmlDocument.Load具有過載,所以沒有必要爲讀者,將直接把文件名。

同樣,當你完成XmlDocument.Save將採取一個文件名,它將保存該文件。

+0

無論如果我使用讀取器或過載的方法,我將最終具有:「該進程無法訪問文件'C:\ MyWebsite \ appAuthentication.xml',因爲它正在被另一個進程使用。」當我使用document.WriteTo(writer)時, – balexandre 2009-01-27 11:07:59

+0

甚至document.Save(作家); – balexandre 2009-01-27 11:09:01

1

您正在更新內存中的節點表示xml文檔,AFAIK無法直接在物理文件中更新節點。您必須將其全部轉儲迴文件。

2

nodeValue屬性可用於更改文本節點的值。

下面的代碼改變第一元素的文本節點值: 示例:

xmlDoc=loadXMLDoc("books.xml"); 

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; 
x.nodeValue="Easy Cooking"; 

源:http://www.w3schools.com/DOM/dom_nodes_set.asp