Reputation: 29248
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
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
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
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
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