How to modify value of an attribute?

  • Thread starter Thread starter shukyh
  • Start date Start date
S

shukyh

Hi All
i have a XML file with 12 element named "device", and attribute named
"project". i wanted to change only the value of one attribute. i tried:

XmlNodeList nList = doc.GetElementsByTagName("device");
foreach (XmlNode node in nList)
{
node.Attributes[@"project"].InnerXml = "aaa";
}


but this modified the attribute in all 12 elements, and not in the
specific node.

what can i do?

thanks
 
Hi Shukyh,
i have a XML file with 12 element named "device", and attribute named
"project". i wanted to change only the value of one attribute.

foreach (XmlNode node in nList)
{
node.Attributes[@"project"].InnerXml = "aaa";
}

Your problem is that you are having a foreach loop without any
conditionality. The GetElementsByTagName() method returns a list of nodes
that match the given name. If you loop through them with foreach, then
naturally all the matching nodes will have their attributes changed.

What you need to do is to figure out which node's attribute you want to
change. If you know the index of the node, then you don't need the foreach
loop at all. Otherwise, you would have an if statement inside the loop to
check to see if you are at the correct node.

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
(e-mail address removed)
http://www.saunalahti.fi/janij/
 
Back
Top