2010-04-01 11 views
25

Już zaimplementowałem, aby utworzyć plik XML poniżej z XmlTextWriter podczas inicjowania aplikacji.Jak zmodyfikować istniejący plik XML za pomocą XmlDocument i XmlNode w C#

I wiem, że nie wiem jak zaktualizować wartość id childNode z XmlDocument & XmlNode.

Czy jest jakaś właściwość do aktualizacji wartości identyfikatora? Próbowałem InnerText, ale nie udało się. Dziękuję Ci.

<?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

nitpicking: przycisk powinien mieć zamykający tag - nie - to nie zadziała, to jest nieprawidłowy XML, tak jak jest poprawiony –

+0

. Dziękuję Ci. –

+0

[Czytanie i pisanie XML przy użyciu C#] (http://www.java2s.com/Code/CSharp/XML/XML-Write.htm) Dlaczego nie wypróbować i nie przyjdzie tutaj z konkretnym pytaniem? pokaż nam również, co zrobiłeś do tej pory. – Shoban

Odpowiedz

50

Trzeba zrobić coś takiego:

// 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

Działa poprawnie! Dziękuję bardzo. –

+1

bardzo proste i optymalne rozwiązanie. Dziękuję Ci. – Nani

+1

Czy można zapisać zmianę w tym samym pliku xml "D: \ test.xml"? –

Powiązane problemy