tags:

views:

180

answers:

4
+3  Q: 

Edit Xml Node

I have an xml document where an xml node with a particular name, say 'Data' can appear anywhere in the xml document i.e anywhere in the hierarchy. I need to read these nodes with their node name alone and edit the node attributes. What is the easiest way to do it?

+1  A: 

Maybe something like this might work for you?

XmlNodeList dataNodes = xmlDocument.SelectNodes('//Data')

foreach(XmlNode node in dataNodes)
{
  .. // do whatever you need to do
}

Marc

marc_s
+2  A: 

Using XPath you can find all Data nodes with:-

foreach(XmlElement elem in dom.SelectNodes("//Data"))
{
    //do stuff to each elem.
}

where dom is an XmlDocument loaded with your Xml.

Alternatively if you prefer XDocument:-

foreach(XElement elem in doc.Descendents("Data"))
{
    //do stuff to each elem.
}
AnthonyWJones
+1  A: 

Something like this:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);

XmlNodeList nodes = xmlDoc.SelectNodes("//Data");
for (int i = 0; i < nodes.Count; i++)
{
    nodes[i].Attributes["somevalue"].Value = "edited";
}

xmlDoc.Save(fileName);
Fredrik Mörk
+3  A: 
XmlDocument doc = new XmlDocument();
doc.Load(@"Test.xml");
XmlNodeList elem = doc.GetElementsByTagName("Data");
foreach (XmlNode tag in elem)
{
 //do whatever you want to the attribute using SetAttribute method
}

XmlElement.GetElementsByTagName Method would do the trick

TStamper
XmlNode has no SetAttribute method. You need to work with XmlElement instead.
Grank