简体   繁体   English

C#中的高级替换

[英]Advanced replace in C#

I like to replace some attributes inside a xml (string) with c#. 我喜欢用c#替换xml(string)中的一些属性。

Example xml: 示例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. 在这种情况下,我喜欢将x属性更改为x和y的组合值。

Result xml: 结果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: 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM