我将要编写一个代码,以在datagirdview与之之间对XML文件进行序列化和反序列化。 对于序列化: 我有2个XML文件,一个叫做 人。 xml
<Person>
<ID> 1 </ ID>
<name> jack </ name>
<Age> 28 </ age>
</ Person>
<Person>
<ID> 2 </ ID>
<name> jacline </ name>
<Age> 22 </ age>
</ Person>
<Person>
<ID> 3 </ ID>
<name> theo </ name>
<Age> 25 </ age>
......
empeloyeur.xml
<Empeloyeur>
<ID> 1 </ ID>
<Job> engineer </ job>
</ Empeloyeur>
<Empeloyeur>
<ID> 2 </ ID>
<Job> Director </ job>
</ Empeloyeur>
.........
我有这段代码可以在datagirdview中显示person.xml文件的内容:
private void fileOpenToolStripMenuItem_Click (object sender, EventArgs e)
{
opf.Filter = "Text documents (.xml) | * .xml";
if (opf.ShowDialog () == DialogResult.OK)
{
string path = opf.FileName;
DataSet dataSet = new DataSet ();
DataSet.ReadXML (path);
dataGridView1.DataSource = dataSet.Tables [0];
}
}
但我想证明在同一datagirdview(datagirdview1)中,文件persone xml文件的属性和empolyeur.xml的属性 那可能吗 ?
对于反序列化xml,我有以下代码
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "person";
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Age");
ds.Tables.Add(dt);
DataRow row = ds.Tables["person"].NewRow();
row["ID"] = textBox1.Text;
row["Name"] = textBox2.Text;
row["Age"] = textBox3.Text;
ds.Tables["person"].Rows.Add(row);
ds.WriteXml(path);
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
但是这段代码最终只给了我最后的属性。我去了一个包含几个celull的文件,不仅是我输入的最后一个
请帮忙吗?
答案 0 :(得分:0)
Xml区分大小写。下面我发布了更新xml文件和代码
Xml 1
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Person>
<ID>1</ID>
<name>jack</name>
<Age>28 </Age>
</Person>
<Person>
<ID>2</ID>
<name>jacline</name>
<Age>22</Age>
</Person>
<Person>
<ID>3</ID>
<name>theo </name>
<Age>25</Age>
</Person>
</root>
Xml 2
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Empeloyeur>
<ID>1</ID>
<Job>engineer </Job>
</Empeloyeur>
<Empeloyeur>
<ID>2</ID>
<Job>Director</Job>
</Empeloyeur>
</root>
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME_1 = @"c:\temp\test1.xml";
const string FILENAME_2 = @"c:\temp\test2.xml";
static void Main(string[] args)
{
XDocument doc1 = XDocument.Load(FILENAME_1);
XDocument doc2 = XDocument.Load(FILENAME_2);
var results = (from d1 in doc1.Descendants("Person")
join d2 in doc2.Descendants("Empeloyeur") on (int)d1.Element("ID") equals (int)d2.Element("ID")
select new { person = d1, empelour = d2 })
.ToList();
DataTable dt = new DataTable("person");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Job", typeof(string));
foreach(var result in results)
{
dt.Rows.Add(new object[] { (int)result.person.Element("ID"), (string)result.person.Element("name"), (int)result.person.Element("Age"), (string)result.empelour.Element("Job") });
}
}
}
}