2016-08-23 40 views
0

下面是一段代碼:LINQ算法從XML創建通用表

XNamespace z = "#SomeSchema"; 
var listCols = new HashSet<Col>(); 
var colNameList = new List<string>(..some values..); 

var xElementList = doc.Descendants(z + "row"); 

return new HashSet<Row>(xElementList .Select(x=> new Row 
     { 
     Col= new List<Col>(listCols).Select(col => 
     { 
      col.Value= (string)x.Attribute(colNameList.First(colName=> colName == col.Name)); 
      return col; 
     }).ToList() 
     })); 

什麼是錯的是,返回值將包含行的名單,但所有這些行有相同的值(對於Col值)。

實施例,行[1] .COL [1]。價值==行[2] .COL [2]。價值

並且這些值應該是完全地不同。我從一個Xml文件中獲取這些值。當我調試xElementList時,值是différents,但是當我嘗試使用它們創建行時,所有行都是相同的。 實際上,行具有相同的列列表,這是xElementList的最後一個記錄。

我做錯了什麼?

謝謝。

回答

3

查看下面的代碼。我讀了兩次xml。一次獲取列名稱並向列添加列。然後第二次讀取xml以獲取行數據。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 
using System.IO; 
using System.Data; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      DataTable dt = new DataTable(); 

      StreamReader sReader = new StreamReader(FILENAME, Encoding.GetEncoding(1252)); 

      XmlReader reader = XmlReader.Create(sReader); 
      Dictionary<string, string> colDict = new Dictionary<string, string>(); 
      while (!reader.EOF) 
      { 
       if (reader.Name != "FIELD") 
       { 
        reader.ReadToFollowing("FIELD"); 
       } 
       if (!reader.EOF) 
       { 
        XElement field = (XElement)XElement.ReadFrom(reader); 
        string attrname = (string)field.Attribute("attrname"); 
        string fieldtype = (string)field.Attribute("fieldtype"); 
        switch (fieldtype) 
        { 
         case "string": 
          dt.Columns.Add(attrname, typeof(string)); 
          break; 
         case "i4": 
          dt.Columns.Add(attrname, typeof(int)); 
          break; 
        } 
        colDict.Add(attrname, fieldtype); 
       } 
      } 
      reader.Close(); 
      sReader = new StreamReader(FILENAME, Encoding.GetEncoding(1252)); 
      reader = XmlReader.Create(sReader); 
      while (!reader.EOF) 
      { 
       if (reader.Name != "ROW") 
       { 
        reader.ReadToFollowing("ROW"); 
       } 
       if (!reader.EOF) 
       { 
        XElement row = (XElement)XElement.ReadFrom(reader); 
        DataRow newRow = dt.Rows.Add(); 
        foreach (XAttribute attrib in row.Attributes()) 
        { 
         string colName = attrib.Name.LocalName; 
         if (colDict.ContainsKey(colName)) 
         { 
          switch (colDict[colName]) 
          { 
           case "string": 
            newRow[colName] = (string)attrib; 
            break; 
           case "i4": 
            newRow[colName] = (int)attrib; 
            break; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+0

謝謝你隊友;)它完美的作品! – Cratebox99