creating a "join" to update one XElement from another XElement
I have an XElement, called "XUsers", that will contain XML which looks like this:
<users>
<user id="12345" name="Bob Smith" />
<user id="67890" name="Jamal Stevens" />
<user id="54321" name="Mary Jones" />
</use开发者_如何学JAVArs>
...and another XElement, called "XTasks", that will contain data like this:
<tasks>
<task id="1" title="Task 1" ownerId="54321" />
<task id="2" title="Task 2" ownerId="12345" />
<task id="3" title="Task 3" ownerId="67890" />
</tasks>
I want to add an attribute ("ownerName") to the task elements in the second XElement (XTasks), and set its values according to a "join" with the first XElement (XUsers). So, my final result will be that the XML in XTask will look like this:
<tasks>
<task id="1" title="Task 1" ownerId="54321" ownerName="Mary Jones" />
<task id="2" title="Task 2" ownerId="12345" ownerName="Bob Smith" />
<task id="3" title="Task 3" ownerId="67890" ownerName="Jamal Stevens" />
</tasks>
Is this possible using Linq? I haven't been able to find any examples of this sort of operation on the web. What is the most efficient way to accomplish this in my ASP.NET(C#) code?
Thanks for any advice you can give.
I am doing this without any IDE in front of me, so forgive me for any errors..
foreach (XElement task in XTasks.Elements())
{
XElement userNode = XUsers.Elements().Where(
e => e.Attribute("id").Value == task.Attribute("ownerId").Value).FirstOrDefault();
if (userNode != null)
{
task.Attribute("ownerName").SetValue(userNode.name);
}
}
精彩评论