Advanced substitution in C #

I like to replace some of the attributes inside the xml (string) in C #.

Example xml:

<items>
  <item x="15" y="25">
    <item y="10" x="30"></item>
  </item>
  <item x="5" y="60"></item>
  <item y="100" x="10"></item>
</items>

      

In this case, I like to change the x-attributes to a combined x and y value.

The xml result:

<items>
  <item x="40" y="25">
    <item y="10" x="40"></item>
  </item>
  <item x="65" y="60"></item>
  <item y="100" x="110"></item>
</items>

      

+2


a source to share


1 answer


Please don't do this with regex. It's very easy with something like LINQ to XML:



XDocument doc = XDocument.Load("input.xml");
foreach (var item in doc.Descendants("item"))
{
    int x = (int) item.Attribute("x");
    int y = (int) item.Attribute("y");
    item.SetAttributeValue("x", x + y);
}
doc.Save("output.xml");

      

+11


a source







All Articles