I need to join two XML documents using LINQ and I'm not sure where to start. I need to join Document 1 and Document 2 on the values of the EmailAddre开发者_运维问答ss nodes and create a final output document that contains the value of the status field from Document 2.
Can anyone help?
Document 1
Document 2
Final Document
The first step is to create a dictionary to map the emails to their status values. Next, select all the email address elements from the first document and set their attributes based on the dictionary.
var dict = secondDoc.Descendants("EmailAddress")
.ToDictionary(e => e.Value, e => e.Attribute("status").Value);
var emails = firstDoc.Descendants()
.Where(e => e.Name.LocalName.StartsWith("EmailAddress")
&& Char.IsDigit(e.Name.LocalName[e.Name.LocalName.Length - 1]));
foreach (var email in emails)
{
string attribute;
if (dict.TryGetValue(email.Value, out attribute))
{
email.SetAttributeValue("status", attribute);
}
}
This approach will directly update firstDoc
; it doesn't create a new XElement
or XDocument
. I added the Char.IsDigit
check to avoid incorrectly matching an EmailAddress
field that doesn't end with a number, should one exist. If you're certain that will never be the case then you can remove that check from the query.
精彩评论