基于c#中的元素值比较两个xml文档中的元素
本文关键字:元素 两个 xml 文档 比较 基于 | 更新日期: 2023-09-27 18:07:10
我试图基于相同的元素连接两个XML,但是我的代码没有返回任何东西。var结果为空。有人能帮忙解决这个问题吗?提前感谢!
文件1:
<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>
元素,然后返回包含bookID
, name
和content
元素的<bookInfo>
元素:
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>