2010-04-01 21 views
25

Ya lo implementé para crear el archivo XML a continuación con XmlTextWriter cuando la inicialización de la aplicación.Cómo modificar el archivo XML existente con XmlDocument y XmlNode en C#

Y sé que no sé cómo actualizar el valor de ID childNode con XmlDocument & XmlNode.

¿Hay alguna propiedad para actualizar el valor de identificación? Intenté InnerText pero falló. gracias.

<?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: el debe tener una etiqueta de cierre - no es una - que no funciona, este no es XML válido como –

+0

corregido. Gracias. –

+0

[Lectura y escritura de XML usando C#] (http://www.java2s.com/Code/CSharp/XML/XML-Write.htm) ¿Por qué no probar y venir aquí con una pregunta específica? también muéstranos qué has hecho hasta ahora. – Shoban

Respuesta

50

que tiene que hacer algo como esto:

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

¡Funciona bien! Muchas gracias. –

+1

solución muy simple y óptima. gracias. – Nani

+1

¿Es posible guardar el cambio en el mismo archivo xml "D: \ test.xml"? –

Cuestiones relacionadas