2012-10-26 80 views
19

我有下面的XML文檔和有一個稱爲在側<FormData>該標籤它作爲一個屬性稱爲FormId =「d617a5e8-b49b-4640-9734-bc7a2bf05691」的標籤如何更改XML文檔中屬性的值?

我想改變該值在C#代碼?

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

要爲我的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> 

回答

23

有這樣的幾個方面,包括:

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

或者這樣:

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

selectSingleNode方法使用XPath來查找節點;有一個關於XPath here的好教程。使用SetAttribute意味着如果FormId屬性不存在,它將被創建,如果它已經存在,則會被更新。

在這種情況下,FORMDATA恰好是文檔的根元素,所以你也可以這樣做:

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

最後這個例子只會工作,你在哪裏改變節點恰好是在根元素該文件。

符合特定FormId GUID(目前尚不清楚,如果這是你想要的):

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

注意,在這個最後的例子選擇返回FORMDATA元素,而不是FormId屬性; []中的表達式使我們能夠搜索具有特定匹配屬性的節點。

+1

+1推薦的XPath,有大量的信息穀歌在XPaths上,它通常比試圖遍歷每個節點更好。 –

+0

非常感謝+1 – Pomster

1

或者你可以明確地走樹:

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

+1。注意這假定FormId屬性已經存在;或者,「xmlDoc.DocumentElement.SetAttribute(」FormId「,」newValue「);」將添加FormId(如果它尚不存在),或者如果它已經更改,則添加它。 – Polyfun

+0

是的,這是一個非常簡單的例子,但您可以根據自己的目的進行修改。 – Davio

4

要選擇合適的節點使用以下XPath //Node[@Attribute='value']

在你的情況的代碼缺少的部分可能看起來像:

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; 
} 

請參閱XPath reference或查看tutorial

+0

+1顯示如何搜索匹配特定GUID的FormId。 – 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

最好的辦法是創建一個可以在任何地方重複使用自己喜歡的功能:

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); 
    }