2016-08-23 54 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