smatter
smatter

Reputation: 29248

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?

Upvotes: 3

Views: 8316

Answers (4)

TStamper
TStamper

Reputation: 30384

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

Upvotes: 4

Fredrik Mörk
Fredrik Mörk

Reputation: 158409

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

Upvotes: 1

AnthonyWJones
AnthonyWJones

Reputation: 189555

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

Upvotes: 3

marc_s
marc_s

Reputation: 755531

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

Upvotes: 1

Related Questions