1

I have two XML files that represents two relational tables that have relation in between. The files are as below: Exam.XML

 <?xml version="1.0" encoding="utf-8" ?>
 <Exam>
   <Student id='1'>
     <result>100 </result>
  </Student >
  <Student id='2'>
     <result>200 </result>
  </Student >
 </Exam> 

Student.XML

 <?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student id='1'>
      <name>John</name>
  </Student >
  <Student id='2'>
     <name>Mark </name>
  </Student >

and the result should be

StudentID StudentName Result

1 John 100

2 Mark 200

How to implement this in c#? Note: my file are not that simple, so merging them will not be helpful

4

2 に答える 2

1

ここで Linq2Xml が役に立ちます。

var list = XDocument.Load("student.xml").Descendants("Student")
             .Join(XDocument.Load("exam.xml").Descendants("Student"),
                   x => x.Attribute("id").Value, 
                   y => y.Attribute("id").Value, 
                   (s, e) => new{
                        Name = s.Element("name").Value,
                        Id = s.Attribute("id").Value,
                        Result = e.Element("result").Value
                    })
             .ToList();

またはクエリ構文で同じこと

var query = from s in XDocument.Load("student.xml").Descendants("Student")
            join e in XDocument.Load("exam.xml").Descendants("Student")
                   on s.Attribute("id").Value equals e.Attribute("id").Value
            select new {
                            Name = s.Element("name").Value,
                            Id = s.Attribute("id").Value,
                            Result = e.Element("result").Value
                       };

var list = query.ToList();
于 2012-11-08T11:50:00.213 に答える
-1

この場合、私は2つのデータテーブルをロードし、プログラムで3番目を作成します

データテーブルへのロードはそのように行うことができます

DataTable newTable = new DataTable();
newTable.ReadXml("FILENAME.xml");

そして、そのようにプログラムで新しいデータテーブルを作成します

    DataTable table = new DataTable(tableName);
    DataColumn column = new DataColumn("id", typeof(System.Int32));
    column.AutoIncrement = true;
    table.Columns.Add(column);

    column = new DataColumn("item", typeof(System.String));
    table.Columns.Add(column);

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = table.NewRow();
        row["item"] = "item " + i;
        table.Rows.Add(row);
    }

    table.AcceptChanges();

これがあなたの質問に答えない場合(より詳細な説明が必要です)これについてコメントし、あなたのために詳しく説明しません:)

そして、質問が役に立った場合は、先に進んでマークを付けてみませんか?

于 2012-11-08T11:29:39.547 に答える