C#中的高级替换 [英] Advanced replace in C#

查看:31
本文介绍了C#中的高级替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢用 c# 替换 xml(字符串)中的一些属性.

I like to replace some attributes inside a xml (string) with c#.

示例 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>

在这种情况下,我喜欢将 x 属性更改为 x 和 y 的组合值.

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

结果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>

推荐答案

请不要使用正则表达式执行此操作.使用 LINQ to XML 之类的东西真的很容易:

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

这篇关于C#中的高级替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆