当我尝试从XML创建dataTable时,为什么要创建多个表?

时间:2016-03-30 15:32:06

标签: c# xml datatable

我正在尝试从XML文件创建DataTable。这是我的代码:

 DataSet ds = new DataSet();
        DataTable sqlTable = new DataTable("SqlTable");
        sqlTable.Columns.Add("Team");
        ds.Tables.Add(sqlTable); 
        if (File.Exists(pathToXmlFile))
        {
            //sqlTable.Tables[0].TableName = "ServerXML";
            //sqlTable.ReadXmlSchema(pathToXmlFile);
            ds.ReadXml(pathToXmlFile);
            foreach (DataColumn column in ds.Tables[0].Columns)
            {
                Console.WriteLine(column.ColumnName);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Console.WriteLine(row[column].ToString());
                }
            }

        }
        else
        {
            File.AppendAllText(pathToLogFile, Environment.NewLine + DateTime.Now + ": ServerXml.xml could not be found. A database table could not be created.");
        }
    }

我遇到的问题是,ds.ReadXml(pathToXmlFile)行正在从XML中生成多个表。以下是XML文件的格式:

<?xml version="1.0" encoding="UTF-8"?>
<items found="132" limit="1000">
    <sampleField>
        <att1>18
        </att1>
        <att2>4343
        </att2>
        <att3>94007961
        </att3>
        <att4>Test
        </att4>
        <att5>Example
        </att5>
    </sampleField>

    <sampleField>
        <att1>40
        </att1>
        <att2>8945
        </att2>
        <att3>94089741
        </att3>
        <att4>Test2
        </att4>
        <att5>Example2
        </att5>
    </sampleField>
</items>

如何创建单个表,<sampleField>标记表示不同的条目?

1 个答案:

答案 0 :(得分:0)

创建一个实体类sampleField

public class sampleField
{
 public string att1{get;set;}
 public string att2{get;set;}
 public string att3{get;set;}
 public string att4{get;set;}
 public string att5{get;set;}
}

使用此助手

public static sampleField  ObjectToXML(string XmlOfAnObject, Type ObjectType) {
  StringReader StrReader = new StringReader(XmlOfAnObject);
  XmlSerializer serializer = new XmlSerializer(ObjectType);
  XmlTextReader XmlReader = new XmlTextReader(StrReader);
  try {
    sampleField AnObject = serializer.Deserialize(XmlReader);
    return AnObject;
  } catch (Exception exp) {
    //Handle Exception Code
  } finally {
    XmlReader.Close();
    StrReader.Close();
  }
}