根据C#中的元素值比较两个xml文档中的元素 [英] Compare elements from two xml documents based on element value in C#

查看:189
本文介绍了根据C#中的元素值比较两个xml文档中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图基于相同的元素连接两个XML,但是我的代码未返回任何内容. var结果为空.有人可以帮忙解决这个问题吗?提前非常感谢!

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!

文件一:

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

我正在寻找的结果是这样的:

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

推荐答案

您要在<bookID>子值上加入<book>元素,然后返回包含bookIDnamecontent元素:

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

Dotnetfiddle Demo

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>

这篇关于根据C#中的元素值比较两个xml文档中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆