Edit Xml Node

I have an xml document where an xml node with a specific name, such as "Data", can appear anywhere in the ie XML document, anywhere in the hierarchy. I need to read these nodes only with their node name and edit the node attributes. What is the easiest way to do this?

+3
source share
4 answers
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 will do the trick

+4
source

Using XPath, you can find all data nodes with: -

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

where dom is the XmlDocument loaded by your Xml.

Alternatively, if you prefer XDocument: -

foreach(XElement elem in doc.Descendents("Data"))
{
    //do stuff to each elem.
}
+3
source

, - ?

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

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

+1

- :

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

Source: https://habr.com/ru/post/1708514/


All Articles