Reputation: 871
I am trying to Join two XML based on the same elements, but my code doesn't return anything. The var result is empty. Can someone please help to sovle the problem? Many thanks in advance!
file one:
<bookstore>
<book>
<bookID>100</bookID>
<name> The cat in the hat </name>
</book>
<book>
<bookID>90</bookID>
<name> another book </name>
</book>
<book>
<bookID>103</bookID>
<name> a new book </name>
</book>
</bookstore>
file two
<bookstore>
<book>
<bookID>100</bookID>
<content> story </content>
</book>
<book>
<bookID>90</bookID>
<content> fiction </content>
</book>
<book>
<bookID>103</bookID>
<content> bio </content>
</book>
</bookstore>
the result I'm looking for is something like:
<result>
<bookInfo>
<bookID>103</bookID>
<name> a new book </name>
<content> bio </content>
<bookInfo>
</result>
The (wrong) code I am currently using is:
var reslut =
from a in fileone.Descendants("bookstore")
join b in filetwo.Descendants("bookstore")
on (string)fileone.Descendants("bookID").First() equals (string)filetwo.Descendants(""bookID"").First()
select new XElement("bookInfo", a, b);
Upvotes: 1
Views: 121
Reputation: 89315
You want to join <book>
elements on <bookID>
child value, and then return<bookInfo>
elements containing bookID
, name
, and content
elements :
var bookInfos =
from a in fileone.Descendants("book")
join b in filetwo.Descendants("book")
on (string)a.Element("bookID") equals (string)b.Element("bookID")
select new XElement("bookInfo",
a.Element("bookID"),
a.Element("name"),
b.Element("content")
);
var result = new XElement("result", bookInfos);
Console.WriteLine(result.ToString());
output :
<result>
<bookInfo>
<bookID>100</bookID>
<name> The cat in the hat </name>
<content> story </content>
</bookInfo>
<bookInfo>
<bookID>90</bookID>
<name> another book </name>
<content> fiction </content>
</bookInfo>
<bookInfo>
<bookID>103</bookID>
<name> a new book </name>
<content> bio </content>
</bookInfo>
</result>
Upvotes: 1