根据 C# 中的元素值比较来自两个 xml 文档的元素

Compare elements from two xml documents based on element value in C#

我正在尝试根据相同的元素加入两个 XML,但我的代码没有 return 任何东西。 var 结果为空。有人可以帮忙解决这个问题吗?非常感谢!

文件一:

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

文件二

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

我正在寻找的结果类似于:

<result>
    <bookInfo>
       <bookID>103</bookID>
       <name> a new book </name>
       <content> bio </content>
    <bookInfo>
 </result>

我目前使用的(错误的)代码是:

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);

您想在 <bookID> 子值上加入 <book> 个元素,然后 return<bookInfo> 个包含 bookIDname 的元素,和 content 个元素:

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());

Dotnetfiddle Demo

输出:

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