开发者

Advanced replace in C#

开发者 https://www.devze.com 2022-12-30 11:47 出处:网络
I like to replace some attributes inside a xml (string) with c#. Example xml: <items> <item x=\"15\" y=\"25\">

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&g开发者_开发百科t;
  <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>


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");
0

精彩评论

暂无评论...
验证码 换一张
取 消