You can use XPath to search for tags. For example, if there are several offer tags in xml and you need to find the one with <categoryId>64</categoryId> , then we write the following XPath: "//offer[categoryId/text()='64']"
// #r "System.Xml.Linq" using System.Xml.Linq; using System.Xml.XPath; using System.Xml; using System.IO; class Xml { static void Update(XElement x) { foreach (var n in x.Descendants("name")) { var d = n.Parent.Element("description"); var v = n.Value; n.Value = d.Value; d.Value = v; } } static void Process(IEnumerable<string> cats, XElement file) { foreach (var cat in cats.Distinct()) { var xs = file.XPathSelectElements("//offer[categoryId/text()='" + cat + "']"); foreach(var x in xs.ToList()) Update(x); } } public static XElement ProcessFile(string cats, string file, int skipFileLines) { var xml = String.Concat(System.IO.File.ReadLines(file).Skip(skipFileLines)); var x = XElement.Parse(xml); Process(File.ReadLines(cats).ToList(), x); return x; } }
var root = @"C:\Temp\"; var x = Xml.ProcessFile(root+"cats.txt", root+"file.xml", 1); x.Save(root + "file.new.xml");
here in Xml.ProcessFile it is passed 1 - so that when loading xml, skip the line <?xml version="1.0" encoding="utf8"?> , since there is an error in it - utf8 , and there should be utf-8 .