Reputation: 571
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 :
ex. aaaa => 4, a => 1, aaa => 3
Result:
<root>
<elements>
<element src="4" />
<element src="1" />
<element src="3" />
</elements>
</root>
Upvotes: 1
Views: 1609
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
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