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
2009-05-17 13:47:12
+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
2009-05-17 13:48:20
+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
2009-05-17 13:49:22
+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
2009-05-17 13:53:24
XmlNode has no SetAttribute method. You need to work with XmlElement instead.
Grank
2009-07-30 19:17:26