Shingo Tada
Shingo Tada

Reputation: 571

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

I'd like to ask about how to replace element in xml for experts.

The xml is like this,

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.
  2. Convert src's value to character number by using Convert(string value) method.

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

  1. Replace src's value.

Result:

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

Upvotes: 1

Views: 1609

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499760

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>. 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.

(If you wanted to be more specific when finding the elements, you could use var attributes = doc.Root.Element("elements").Elements("element").Attributes("src");.)

Upvotes: 1

yamen
yamen

Reputation: 15618

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>

Upvotes: 3

Related Questions