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

时间:2021-02-04 19:35:29

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文档,有一个标签叫做 ,在这个标签中它是一个名为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:

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

6 个解决方案

#1


24  

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.

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

#2


4  

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 reference or check this tutorial.

参见XPath参考或检查本教程。

#3


1  

Or you could walk the tree explicitly:

或者你可以明确地走到树上:

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

#4


1  

You can use SetAttribute method http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.setattribute.aspx

可以使用SetAttribute方法http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.setattribute.aspx

#5


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

#6


1  

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

#1


24  

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.

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

#2


4  

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 reference or check this tutorial.

参见XPath参考或检查本教程。

#3


1  

Or you could walk the tree explicitly:

或者你可以明确地走到树上:

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

#4


1  

You can use SetAttribute method http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.setattribute.aspx

可以使用SetAttribute方法http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.setattribute.aspx

#5


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

#6


1  

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