I have some xml files that have some nodes like (among other nodes)
<disp-formula id="deqn*">
...\tag{1}
</disp-formula>
<disp-formula id="deqn*">
...\tag{2}
</disp-formula>
<disp-formula id="deqnxyz">
...\tag{3}
...
...\tag{4}
...\tag{5}...
...
......\tag{6}
</disp-formula>
I'm trying to get the values inside the string/strings \tag{} which is inside the nodes with an attribute named id and modify it with the value/values inside its respective tag{} i.e. the output should be
<disp-formula id="deqn1">
...\tag{1}
</disp-formula>
<disp-formula id="deqn2">
...\tag{2}
</disp-formula>
<disp-formula id="deqn3-6">
...\tag{3}
...
...\tag{4}
...\tag{5}...
...
......\tag{6}
</disp-formula>
I've done
//for nodes containing single \tag{}
Regex regex = new Regex(@"(?<=\\tag\{)(\w+)(?=\})");
var xml = File.ReadAllText(@"D:\Test\sample.xml");
var xdoc = Xdocument.Parse(xml, LoadOptions.PreserveWhitespace);
var _descriptions = xdoc.Descendants("disp-formula")
.Where(x => regex.Match(x.Value).Success);
foreach (var description in _descriptions)
{
var _Result = regex.Match(description.Value).Value;
description.Attribute("id").Value = "deqn" + _Result;
xdoc.Save(@"D:\Test\sample.xml", SaveOptions.DisableFormatting);
}
//for nodes containing multiple \tag{}'s
var descriptions = xdoc.Descendants("disp-formula")
.Where(x => regex.Matches(x.Value).Count > 1);
foreach (var description in descriptions)
{
var p = regex.Matches(description.Value).Cast<Match>().Select(m => m.Value).ToArray();
var x = p[0];
var y = p[p.Count() - 1];
var Result = x + "-" + y;
description.Attribute("id").Value = "deqn" + Result;
xdoc.Save(@"D:\Test\sample.xml", SaveOptions.DisableFormatting);
}
How do I make this code more efficient?