views:

109

answers:

1

Hi, I like to replace some attributes inside a xml (string) with 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 the combined value of x and y.

Result xml:

<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>
+11  A: 

Please don't do this with a regex. It's really 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");
Jon Skeet
Thanks, worked great!
Andreas