2012-10-26 16 views
19

Ho un documento XML qui sotto e c'è un tag denominato <FormData> in parte questo tag come un attributo chiamato formid = "d617a5e8-b49b-4640-9734-bc7a2bf05691"Come modificare il valore di un attributo in un documento XML?

vorrei cambiare quel valore nel codice C#?

XmlDocument xmlDoc = new XmlDocument(); 
    xmlDoc.Load(MapPath(tempFolderPathAlt + "dvforms" + "\\XmlDataTemplate.xml")); 
    //Change value of FormID 
    xmlDoc.Save(tempFolderPath + "data.xml"); 

Essere è il mio documento XML:

<?xml version="1.0"?> 
<FormData Platform="Android" PlatformVersion="100" Version="966" DataVersion="1" Description="Investec - Res" FormId="d617a5e8-b49b-4640-9734-bc7a2bf05691" FileId="e6202ba2-3658-4d8e-836a-2eb4902d441d" EncryptionVerification="" CreatedBy="Bob" EditedBy="Bob"> 
<FieldData> 
<request_details_export_template Mod="20010101010101" IncludeInPDFExport="Yes"></request_details_export_template> 
<request_details_reason_for_valuatio Mod="20010101010101" IncludeInPDFExport="Yes"></request_details_reason_for_valuatio> 
</FieldData> 
<Photos Mod="20010101010101"/> 
<VoiceNotes/> 
<Drawings Mod="20010101010101"/> 
<FieldNotes/> 
</FormData> 

risposta

23

Ci sono diversi modi per farlo, tra cui:

XmlAttribute formId = (XmlAttribute)xmlDoc.SelectSingleNode("//FormData/@FormId"); 
if (formId != null) 
{ 
    formId.Value = "newValue"; // Set to new value. 
} 

O questo:

XmlElement formData = (XmlElement)xmlDoc.SelectSingleNode("//FormData"); 
if (formData != null) 
{ 
    formData.SetAttribute("FormId", "newValue"); // Set to new value. 
} 

Il metodo SelectSingleNode usa XPath per trovare il nodo; c'è un buon tutorial su XPath here. Utilizzando SetAttribute, l'attributo FormId verrà creato se non esiste già o aggiornato se esiste già.

In questo caso, formdata sembra essere l'elemento radice del documento, in modo da poter eseguire questa operazione:

xmlDoc.DocumentElement.SetAttribute("FormId", "newValue"); // Set to new value. 

Quest'ultimo esempio funziona solo se il nodo si modifica sembra essere l'elemento radice il documento.

per abbinare una specifica guid formid (non è chiaro se questo è quello che si voleva):

XmlElement formData = (XmlElement)xmlDoc.SelectSingleNode("//FormData[@FormId='d617a5e8-b49b-4640-9734-bc7a2bf05691']"); 
if (formData != null) 
{ 
    formData.SetAttribute("FormId", "newValue"); // Set to new value. 
} 

Si noti che la selezione in questo ultimo esempio restituisce l'elemento formdata e non l'attributo formid; l'espressione tra parentesi [] ci consente di cercare un nodo con un particolare attributo di corrispondenza.

+1

+1 per raccomandare XPaths, c'è un sacco di informazioni per Google su XPath e di solito è meglio che cercare di attraversare ogni nodo. –

+0

Grazie grande risposta +1 – Pomster

1

Oppure si può andare a piedi l'albero in modo esplicito:

xmlDoc.DocumentElement.GetAttribute("FormId").Value = ""; 
+0

+1. Nota questo presuppone che l'attributo FormId esista già; in alternativa, "xmlDoc.DocumentElement.SetAttribute (" FormId "," newValue ");" aggiungerà il FormId se non esiste già, o lo cambierà se lo fa. – Polyfun

+0

Sì, questo è un esempio molto semplice, ma è possibile modificarlo per il proprio scopo. – Davio

4

Per selezionare l'uso del nodo a destra seguendo XPath //Node[@Attribute='value'].

Nel tuo caso il pezzo mancante del codice potrebbe essere simile:

var formId = "d617a5e8-b49b-4640-9734-bc7a2bf05691"; 
var newId = "[set value here]"; 

var xpath = String.Format("//FormData[@FormId='{0}']", formId); 

XmlNode node = xmlDoc.SelectSingleNode(xpath); 

if(node != null) 
{ 
    node.Attributes["FormId"].Value = newId; 
} 

Vedere XPath reference o controllare questo tutorial.

+0

+1 per mostrare come cercare un FormId che corrisponde a un guid specifico. – Polyfun

1
XDocument doc = XDocument.Load(m_pFileName);     
XElement xElemAgent = doc.Descendants("TRAINEE") 
.Where(arg => arg.Attribute("TRAINEEID").Value == m_pTraineeID.ToString()).Single(); 
xElemAgent.SetAttributeValue("FIRSTNAME",m_pFirstName); 
xElemAgent.SetAttributeValue("LASTNAME", m_pLastName); 
xElemAgent.SetAttributeValue("DOB",m_pDOB); 
xElemAgent.SetAttributeValue("UNIQUEID",m_pUniqueID); 
doc.Save(m_pFileName); 
1

il modo migliore è quello di creare una funzione che può essere riutilizzato ovunque vi piace:

public void ReplaceXMLAttributeValueByIndex(string fullFilePath, string nodeName, int index, string valueToAdd) 
    { 
     FileInfo fileInfo = new FileInfo(fullFilePath); 
     fileInfo.IsReadOnly = false; 
     fileInfo.Refresh(); 

     XmlDocument xmldoc = new XmlDocument(); 
     xmldoc.Load(fullFilePath); 
     try 
     { 
      XmlNode node = xmldoc.SelectSingleNode(nodeName); 
      node.Attributes[index].Value = valueToAdd; 
     } 
     catch (Exception ex) 
     { 
      //add code to see the error 
     } 
     xmldoc.Save(fullFilePath); 
    } 
Problemi correlati