[英]Join 3 XML document at specific attribute and get single XML document using LINQ in C#
<--INPUT XML file #1-->
<name_info>
<person id = "101">
<name>"Thomas Edison"<name>
<age>"35"</age>
</person>
<person id = "102">
<name>"Louis Pasture"<name>
<age>"40"</age>
</person>
</name_info>
<--INPUT XML file #2-->
<phone_info>
<person id = "101">
<phone>"7777777777"</phone>
</person>
<person id = "102">
<phone>"99999999"</phone>
</person>
</phone_info>
<--INPUT XML file #3-->
<country_info>
<person id = "101">
<country>"England"</country>
</person>
<person id = "102">
<country>"Paris"</country>
</person>
</country_info>
<--OUTPUT XML file #4-->
<person>
<person id = "101">
<name>"Thomas Edison"<name>
<age>"35"</age>
<phone>"7777777777</phone>
<country>"England"</country>
</person>
<person id = "102">
<name>"Louis Pasture"<name>
<age>"40"</age>
<phone>"99999999</phonephone>
<country>"Paris"</country>
</person>
<person/>
Xml Attributes value need double quotes around the values like Xml 属性值需要在值周围加上双引号,例如
See xml linq solution below:请参阅下面的 xml linq 解决方案:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication4
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
const string FILENAME1 = @"c:\temp\test1.xml";
const string FILENAME2 = @"c:\temp\test2.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XDocument doc1 = XDocument.Load(FILENAME1);
XDocument doc2 = XDocument.Load(FILENAME2);
var joins = (from d in doc.Descendants("person")
join d1 in doc1.Descendants("person") on (int)d.Attribute("id") equals (int)d1.Attribute("id")
join d2 in doc2.Descendants("person") on (int)d.Attribute("id") equals (int)d2.Attribute("id")
select new { d = d, d1 = d1, d2 = d2 }
).ToList();
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <person></person>";
XDocument outputXml = XDocument.Parse(ident);
XElement persons = outputXml.Root;
foreach (var join in joins)
{
XElement person = XElement.Parse(join.d.ToString());
person.Add(XElement.Parse(join.d1.Element("phone").ToString()));
person.Add(XElement.Parse(join.d2.Element("country").ToString()));
persons.Add(person);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.