1

I am recently working on a .net 2.0 project I have to read some xml files and replace certain elements value. Wondering how you do it the following not using linq to xml?

 IEnumerable<XElement> cities= xmldoc.Descendants("City")
            .Where(x => x.Value == "London");


        foreach (XElement myElem in cities)
        {
            myElem.ReplaceWith(new XElement("City", "NewCity"));
        }

or

       var xElement = xdoc.Descendants("FirstName").Where(x => x.Value == "Max").First();
        xElement.ReplaceWith(new XElement("FirstName", "NewValue");

Any suggestions

user9969
  • 15,034
  • 37
  • 104
  • 173

2 Answers2

1

You will need to use XmlDocument and query it using XPath with SelectNodes.

It will not be as nice and succint.

Oded
  • 477,625
  • 97
  • 867
  • 998
1

You can consider using XmlDocument, like this:

string xmlFile = "<xml><data<test /><test /><test /><test /></data></xml>";
var xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);

var oNodes = xmlDoc.SelectNodes("//test");
foreach (var oNode in oNodes)
{
   oNode.InnerText = "bla bla"; 
}

xmlDoc.Save("..path to xml file");

(In your case you can use InnerXml property of the document)

http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx

To selectNodes you should pass XPath Query, reference can be found:

http://www.w3schools.com/xpath/

Also if you XML contains namespace, you need to use XmlNamespaceManager:

http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.aspx

Otherwise xpath won't work.

Kamil Lach
  • 4,359
  • 2
  • 18
  • 20