2010-04-01 40 views
25

我已經實現了用於在創建下面的XML文件時使用XmlTextWriter當應用程序初始化時。如何使用C#中的XmlDocument和XmlNode修改現有的XML文件

而且知道,我不知道如何與的XmlDocument & XmlNode的更新值childNode ID。

是否有一些屬性更新id值?我試過InnerText但失敗。謝謝。

<?xml version="1.0" encoding="UTF-8"?> 
<Equipment xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <License licenseId="" licensePath=""/> 
    <DataCollections> 
    <GroupAIDs> 
     <AID id="100"> 
     <Variable id="200"/> 
     <Variable id="201"/> 
     </AID> 
     <AID id=""> 
     <Variable id="205"/> 
     </AID> 
     <AID id="102"/> 
    </GroupAIDs> 
    <GroupBIDs> 
     <BID id="2000"> 
     <AID id="100"/> 
     </BID> 
     <BID id="2001"> 
     <AID id="101"/> 
     <AID id="102"/> 
     </BID> 
    </GroupBIDs> 
    <GroupCIDs> 
     <BID id="8"/> 
     <BID id="9"/> 
     <BID id="10"/> 
    </GroupCIDs> 
    </DataCollections> 
</Equipment> 
+0

挑剔:在應該有一個關閉標籤 - 不是 - 這是行不通的,這無效,因爲 – 2010-04-01 07:53:56

+0

已更正。謝謝。 – 2010-04-01 08:07:01

+0

[使用c#讀取和寫入XML](http://www.java2s.com/Code/CSharp/XML/XML-Write.htm)爲什麼不試試並帶一個具體問題來這裏?也告訴我們你到目前爲止做了什麼。 – Shoban 2010-04-01 07:29:03

回答

50

你需要做這樣的事情:

// instantiate XmlDocument and load XML from file 
XmlDocument doc = new XmlDocument(); 
doc.Load(@"D:\test.xml"); 

// get a list of nodes - in this case, I'm selecting all <AID> nodes under 
// the <GroupAIDs> node - change to suit your needs 
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID"); 

// loop through all AID nodes 
foreach (XmlNode aNode in aNodes) 
{ 
    // grab the "id" attribute 
    XmlAttribute idAttribute = aNode.Attributes["id"]; 

    // check if that attribute even exists... 
    if (idAttribute != null) 
    { 
     // if yes - read its current value 
     string currentValue = idAttribute.Value; 

     // here, you can now decide what to do - for demo purposes, 
     // I just set the ID value to a fixed value if it was empty before 
     if (string.IsNullOrEmpty(currentValue)) 
     { 
     idAttribute.Value = "515"; 
     } 
    } 
} 

// save the XmlDocument back to disk 
doc.Save(@"D:\test2.xml"); 
+0

它工作正常!非常感謝。 – 2010-04-01 08:14:20

+1

非常簡單和最佳的解決方案。謝謝。 – Nani 2016-09-15 14:49:22

+1

是否可以將更改保存在同一個xml文件「D:\ test.xml」中? – 2016-09-18 05:22:00