2012-08-10 17 views
8

Ho un XML (questo è esattamente quello che sembra):come cambiare nodo XML valori

<PolicyChangeSet schemaVersion="2.1" username="" description=""> 
    <Attachment name="" contentType=""> 
     <Description/> 
     <Location></Location> 
    </Attachment> 
</PolicyChangeSet> 

Questo è in macchina dell'utente.

Devo aggiungere valori a ciascun nodo: nome utente, descrizione, nome allegato, tipo di contenuto e posizione.

Questo è quello che ho finora:

string newValue = string.Empty; 
      XmlDocument xmlDoc = new XmlDocument(); 

      xmlDoc.Load(filePath); 
      XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); 
      node.Attributes["username"].Value = AppVars.Username; 
      node.Attributes["description"].Value = "Adding new .tiff image."; 
      node.Attributes["name"].Value = "POLICY"; 
      node.Attributes["contentType"].Value = "content Typeeee"; 

      //node.Attributes["location"].InnerText = "zzz"; 

      xmlDoc.Save(filePath); 

Qualsiasi aiuto?

risposta

13

Con XPath. XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); seleziona il nodo principale.

+1

che ha funzionato :) ... posso solo accettare la tua risposta in 10 minuti tho. grazie Jan! – Testifier

+0

come aggiungerei comunque un valore per "posizione"? è solo tra lo <> ... ?? – Testifier

+0

Anytime :) Osserva la proprietà 'InnerText' di XmlNode. – Jan

3

Got con questo -

xmlDoc.Load(filePath); 
      XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); 
      node.Attributes["username"].Value = AppVars.Username; 
      node.Attributes["description"].Value = "Adding new .tiff image."; 

      node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment"); 
      node.Attributes["name"].Value = "POLICY"; 
      node.Attributes["contentType"].Value = "content Typeeee"; 
xmlDoc.Save(filePath); 
2

utilizzare LINQ to XML :)

XDocument doc = XDocument.Load(path); 
IEnumerable<XElement> policyChangeSetCollection = doc.Elements("PolicyChangeSet"); 

foreach(XElement node in policyChangeSetCollection) 
{ 
    node.Attribute("username").SetValue(someVal1); 
    node.Attribute("description").SetValue(someVal2); 
    XElement attachment = node.Element("attachment"); 
    attachment.Attribute("name").SetValue(someVal3); 
    attachment.Attribute("contentType").SetValue(someVal4); 
} 

doc.Save(path); 
2
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Description").InnerText = "My Desciption"; 
xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/Location").InnerText = "My Location"; 
0
For setting value to XmlNode: 
XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); 
      node["username"].InnerText = AppVars.Username; 
      node["description"].InnerText = "Adding new .tiff image."; 
      node["name"].InnerText = "POLICY"; 
      node["contentType"].InnerText = "content Typeeee"; 

For Getting value to XmlNode: 
username=node["username"].InnerText 
Problemi correlati