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

时间:2015-08-09 03:45:36

标签: c# xml linq join element

我正在尝试基于相同的元素加入两个XML,但我的代码并没有返回任何内容。 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);

1 个答案:

答案 0 :(得分:1)

您希望在<book>子级值上加入<bookID>元素,然后返回包含<bookInfo>bookIDname的{​​{1}}个元素要素:

content

<强> Dotnetfiddle Demo

输出

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