C# 如何更改XML文档中属性的值?

C# 如何更改XML文档中属性的值?,c#,xml,C#,Xml,我在下面有一个XML文档,在这侧有一个名为的标记,它作为一个名为FormId的属性来标记它。=“d617a5e8-b49b-4640-9734-bc7a2bf05691” 我想在C代码中更改该值 Be是我的XML文档: <?xml version="1.0"?> <FormData Platform="Android" PlatformVersion="100" Version="966" DataVersion="1" Description="Investec - Res"

我在下面有一个XML文档,在这侧有一个名为
的标记,它作为一个名为FormId的属性来标记它。=“d617a5e8-b49b-4640-9734-bc7a2bf05691”

我想在C代码中更改该值

Be是我的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>


有几种方法可以做到这一点,包括:

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有一个很好的教程。使用SetAttribute意味着如果FormId属性不存在,将创建该属性;如果FormId属性已经存在,则更新该属性

在这种情况下,FormData恰好是文档的根元素,因此您也可以执行以下操作:

xmlDoc.DocumentElement.SetAttribute("FormId", "newValue"); // Set to new value.
最后一个示例仅适用于您正在更改的节点恰好是文档中的根元素的情况

要匹配特定的FormId guid(不清楚这是否是您想要的):


注意,最后一个示例中的select返回FormData元素,而不是FormId属性;[]括号中的表达式使我们能够搜索具有特定匹配属性的节点。

或者您可以显式遍历树:

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

要选择正确的节点,请使用以下XPath
//节点[@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或选中此项。

您可以使用SetAttribute方法

最好的方法是创建一个可以在任何地方重用的函数:

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

+1对于推荐XPath,Google在XPath上有大量信息,通常比尝试遍历每个节点要好。+1。注意:这假设FormId属性已经存在;或者,“xmlDoc.DocumentElement.SetAttribute(“FormId”,“newValue”);”将添加FormId(如果它不存在),或者更改它。是的,这是一个非常简单的示例,但您可以出于自己的目的对其进行更改。+1用于显示如何搜索与特定guid匹配的FormId。
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;
}
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);
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);
    }