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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13083044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:34:35  来源:igfitidea点击:

How to change the value of an attribute in an XML document?

c#xml

提问by Pomster

I have an XML document below and there is a tag called <FormData>in side this tag it as an attribute called FormId="d617a5e8-b49b-4640-9734-bc7a2bf05691"

我在下面有一个 XML 文档,<FormData>在这个标签旁边有一个标签,它作为一个名为FormId="d617a5e8-b49b-4640-9734-bc7a2bf05691"的属性

I would like to change that value in C# code?

我想在 C# 代码中更改该值?

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

Be is my XML document:

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>

采纳答案by Polyfun

There are several ways of doing this, including:

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

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

Or this:

或这个:

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

The SelectSingleNode method uses XPath to find the node; there is a good tutorial about XPath here. Using SetAttribute means the FormId attribute will be created if it does not already exist, or updated if it does already exist.

SelectSingleNode 方法使用 XPath 来查找节点;有有关XPath的一个很好的教程在这里。使用 SetAttribute 意味着 FormId 属性在它不存在时将被创建,或者如果它已经存在则更新。

In this case, FormData happens to be the document's root element, so you can also do this:

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

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

This last example will only work where the node you are changing happens to be the root element in the document.

最后一个示例仅适用于您正在更改的节点恰好是文档中的根元素的情况。

To match a specific FormId guid (it is not clear if this is what you wanted):

要匹配特定的 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.
}

Note that the select in this last example returns the FormData element and not the FormId attribute; the expression in [] brackets enables us to search for a node with a particular matching attribute.

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

回答by Davio

Or you could walk the tree explicitly:

或者你可以明确地走树:

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

回答by Michal Klouda

To select the right node use following XPath //Node[@Attribute='value'].

要选择正确的节点,请使用以下 XPath //Node[@Attribute='value']

In your case the missing piece of code could look like:

在您的情况下,丢失的代码可能如下所示:

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

See XPath referenceor check this tutorial.

请参阅 XPath参考或查看本教程

回答by user2919709

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

回答by test

the best way is to create a function that can be reused anywhere you like:

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

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