在C#中使用XPath查询加入两个xml文件

时间:2015-07-31 03:07:05

标签: c# xml xpath

我是C#的新手,我有两个xml文件,它们作为XDocument加载到我的程序中。我想找到一种方法来执行内连接并将结果存储为新文件。我不确定如何通过使用XPath查询来实现这一点。

说这是我的第一个xml文件:

<?xml version="1.0" encoding="utf-8"?>

<People>
  <Person>
    <ID> 1 </ID>
    <Gender> M </Gender>
  </Person>

  <Person>
    <ID> 2 </ID>
    <Gender> F </Gender>
  </Person>
</People>

这是我的第二个xml文件:

<?xml version="1.0" encoding="utf-8"?>

<PeopleDetail>
  <PersonDetail>
    <ID> 1 </ID>
    <Name> ABC </Name>
  </PersonDetail>

  <PersonDetail>
    <ID> 2 </ID>
    <Name> DEF </Name>
  </PersonDetail>
</PeopleDetail>

我想得到的是这样的东西:

<Output>
  <Join>
    <Person>
      <ID> 1 </ID>
      <Gender> M </Gender>
    </Person>
    <PersonDetail>
      <ID> 1 </ID>
      <Name> ABC </Name>
    </PersonDetail>
  </Join> 

  <Join>
    <Person>
      <ID> 2 </ID>
      <Gender> F </Gender>
    </Person>
    <PersonDetail>
      <ID> 2 </ID>
      <Name> DEF </Name>
    </PersonDetail>
  </Join> 
</Output>

使用XDocument.Load()方法将两个文件加载到我的程序中:

var doc1 = XDocument.Load("first.xml");
var doc2 = XDocument.Load("second.xml");

那么有人能告诉我如何通过“ID”执行这样的内部联接吗?

由于

1 个答案:

答案 0 :(得分:1)

我不确定XPath在这里对你有多大用处,但是你可以使用LINQ进行简单的连接并创建一个包含这些元素的新文档。为清楚起见,我已将doc1doc2重命名为peopledetails

var joins = from person in people.Descendants("Person")
            join detail in details.Descendants("PersonDetail")
                on (int)person.Element("ID") equals (int)detail.Element("ID")
            select new XElement("Join", person, detail);

var output = new XDocument(
    new XElement("Output",
        joins
        )
    );

您可以在此处查看有效的演示:https://dotnetfiddle.net/HP5VtD