简体   繁体   English

Linq(C#):如何替换xml中的元素

[英]Linq (C#) : how to replace element in xml

I'd like to ask about how to replace element in xml for experts. 我想问一下如何为专家替换xml中的元素。

The xml is like this, xml是这样的,

Source: 资源:

<root>
    <elements>
        <element src="aaaa" />
        <element src="a" />
        <element src="aaa" />
    </elements>
</root>

What I'd like to do is : 我想做的是:

  1. Find src element's value. 找到src元素的值。
  2. Convert src's value to character number by using Convert(string value) method. 使用Convert(字符串值)方法将src的值转换为字符数。

ex. 恩。 aaaa => 4, a => 1, aaa => 3 aaaa => 4,a => 1,aaa => 3

  1. Replace src's value. 替换src的值。

Result: 结果:

<root>
    <elements>
        <element src="4" />
        <element src="1" />
        <element src="3" />
    </elements>
</root> 

Is this what you're after? 这就是你要追求的吗?

var source = "<root><elements><element src=\"aaaa\"/><element src=\"a\"/>" +
             "<element src=\"aaa\"/></elements></root>";

var doc = XElement.Parse(source);

foreach (var element in doc.Descendants("element"))
{
    element.Attribute("src").Value = element.Attribute("src").Value.Length.ToString();
}

Results in: 结果是:

<root>
  <elements>
    <element src="4" />
    <element src="1" />
    <element src="3" />
  </elements>
</root>

A slight alternative to the options given in other answers: 与其他答案中给出的选项略有不同:

var attributes = doc.Descendants("element").Attributes("src");
foreach (var attribute in attributes)
{
    attribute.Value = attribute.Value.Length.ToString();
}

This uses the Attributes extension method on IEnumerable<XElement> . 这在IEnumerable<XElement>上使用Attributes扩展方法。 It makes the code slightly simpler than fetching the attribute within the loop, IMO - and certainly simpler than fetching it on both the left and right hand sides of the assignment operator. 它使得代码比在循环中获取属性(IMO)稍微简单一点 - 当然比在赋值运算符的左侧和右侧获取它更简单。

(If you wanted to be more specific when finding the elements, you could use var attributes = doc.Root.Element("elements").Elements("element").Attributes("src"); .) (如果您想在查找元素时更具体,可以使用var attributes = doc.Root.Element("elements").Elements("element").Attributes("src");

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

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