以下代码是读取xml的内容,包括列字段信息和表数据.采用线程读取各个表的数据.针对特定的XML格式
private string fileName; private XmlTextWriter writer; /// <summary> /// 数据库类型 /// </summary> private DataBaseType dataBaseType; /// <summary> /// 表名 /// </summary> private DataTable tableNames = new DataTable(); private Dictionary<string, DataTable> tableSchemas = new Dictionary<string, DataTable>(); private Dictionary<string, DataTable> tableDatas = new Dictionary<string, DataTable>(); private Dictionary<string, string> tableSQLs = new Dictionary<string, string>(); private Dictionary<string, DataTable> tableColInfos = new Dictionary<string, DataTable>(); /// <summary> /// 读取数据时必须先调用 LoadOffLineData() /// 写数据时必须先调用 InitXmlTextWriter() /// </summary> /// <param name="fileName"></param> public FileHelper(string fileName) { this.fileName = fileName; }
相关定义
/// <summary> /// 根据类型名称获取对应的类型 /// </summary> /// <param name="typeName"></param> /// <returns></returns> private Type GetType(string typeName) { Type type = typeof(Object); typeName = typeName.ToLower().Trim(); switch (dataBaseType) { case DataBaseType.Access: break; case DataBaseType.DB2: break; case DataBaseType.MySql: break; case DataBaseType.Odbc: break; case DataBaseType.Oracle: break; case DataBaseType.SqlCe: break; case DataBaseType.SqlServer: switch (typeName) { case "int": case "smallint": case "bigint": type = typeof(int); break; case "bit": type = typeof(Boolean); break; case "datetime": case "smalldatetime": type = typeof(DateTime); break; case "decimal": case "numeric": case "smallmoney": type = typeof(Decimal); break; case "float": type = typeof(Double); break; case "image": case "money": case "binary": case "sql_variant": case "timestamp": case "varbinary": case "uniqueidentifier": case "xml": type = typeof(Object); break; case "ntext": case "varchar": case "nvarchar": case "text": case "nchar": case "char": type = typeof(String); break; case "real": type = typeof(Single); break; case "tinyint": type = typeof(Byte); break; } break; } return type; }
GetType
/// <summary> /// 加载离线数据 /// </summary> /// <returns></returns> public bool LoadOffLineData() { XmlTextReader reader = new XmlTextReader(fileName); tableNames.Columns.Add("name"); if (reader.ReadToFollowing("database")) { try { dataBaseType = (DataBaseType)Enum.Parse(typeof(DataBaseType), reader.GetAttribute("databasetype")); while (reader.ReadToFollowing("table")) { tableNames.Rows.Add(reader.GetAttribute("name")); Thread th = new Thread(AnalyzeTableXml); th.Start(reader.ReadOuterXml()); } } catch (Exception err) { dataBaseType = DataBaseType.SqlServer; this.LogWrite(LogType.Error, "加载离线数据出错!", err); return false; } } reader.Close(); return true; }
LoadOffLineData
/// <summary> /// 分析表结构与读取表数据 /// </summary> /// <param name="obj"></param> private void AnalyzeTableXml(object obj) { string tableName = ""; try { XmlTextReader reader = new XmlTextReader(obj.ToString(), XmlNodeType.Document, null); if (reader.ReadToFollowing("table")) { //作为Key值,表名全为小写 tableName = reader.GetAttribute("name").Trim().ToLower(); DataTable dtSchema = new DataTable(); DataTable dtColInfo = new DataTable(); DataTable dataDt = new DataTable(); dtSchema.TableName = tableName; dtColInfo.TableName = tableName; dataDt.TableName = tableName; tableSchemas.Add(tableName, dtSchema); tableColInfos.Add(tableName, dtColInfo); tableDatas.Add(tableName, dataDt); //读取建表语句 if (reader.ReadToDescendant("createsql") && !reader.IsEmptyElement) { tableSQLs.Add(tableName, reader.ReadElementString().Trim()); } else { this.LogWrite(LogType.Info, "表[{0}]没有建表语句!".Formats(tableName)); } //读取列(结构) if (reader.ReadToNextSibling("columns") && !reader.IsEmptyElement) { //第一列 if (reader.ReadToDescendant("column")) { AddColumn(reader, dtSchema); AddColInfo(reader, dtColInfo); dataDt.Columns.Add(reader.GetAttribute("col_name"));//添加列 //循环读取其它列 while (reader.ReadToNextSibling("column")) { AddColumn(reader, dtSchema); AddColInfo(reader, dtColInfo); dataDt.Columns.Add(reader.GetAttribute("col_name"));//添加列 } } } else { this.LogWrite(LogType.Info, "表[{0}]没有结构信息!".Formats(tableName)); return; } //读取行(数据) if (reader.ReadToNextSibling("rows") && !reader.IsEmptyElement) { //第一行 if (reader.ReadToDescendant("row") && !reader.IsEmptyElement) { do { //第一单元格 if (reader.ReadToDescendant("cell")) { DataRow dr = dataDt.Rows.Add(); dr[reader.GetAttribute("columnname")] = reader.ReadElementString().Trim(); //循环读取其它单元格 while (reader.ReadToNextSibling("cell")) { dr[reader.GetAttribute("columnname")] = reader.ReadElementString().Trim(); } } } while (reader.ReadToNextSibling("row") && !reader.IsEmptyElement); } } } reader.Close(); } catch (Exception err) { this.LogWrite(LogType.Error, "分析表[{0}]XML出错!".Formats(tableName), err); } }
AnalyzeTableXml
/// <summary> /// 添加列 /// </summary> /// <param name="reader"></param> /// <param name="dtSchema"></param> private void AddColumn(XmlTextReader reader, DataTable dtSchema) { DataColumn dc = dtSchema.Columns.Add(reader.GetAttribute("col_name")); dc.DataType = GetType(reader.GetAttribute("col_typename")); dc.AllowDBNull = bool.Parse(reader.GetAttribute("col_null")); dc.AutoIncrement = bool.Parse(reader.GetAttribute("col_identity") == "" ? "false" : reader.GetAttribute("col_identity")); if (dc.AutoIncrement) { dc.AutoIncrementSeed = long.Parse(reader.GetAttribute("col_seed") == "" ? "0" : reader.GetAttribute("col_seed")); dc.AutoIncrementStep = long.Parse(reader.GetAttribute("col_increment") == "" ? "0" : reader.GetAttribute("col_increment")); } if (dc.DataType == typeof(string)) { dc.MaxLength = Int32.Parse(reader.GetAttribute("col_len") == "" ? Int64.MaxValue.ToString() : reader.GetAttribute("col_len")); } }
AddColumn
/// <summary> /// 添加列的行信息 /// </summary> /// <param name="reader"></param> /// <param name="dtColInfo"></param> private void AddColInfo(XmlTextReader reader, DataTable dtColInfo) { DataRow dr = dtColInfo.Rows.Add(); for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); if (!dtColInfo.Columns.Contains(reader.Name)) { dtColInfo.Columns.Add(reader.Name); } dr[reader.Name] = reader.Value; } }
AddColInfo
<?xml version="1.0" encoding="utf-8"?> <database databasetype="0"> <tables> <table name="IncidentTemplate"> <createsql>CREATE TABLE [dbo].[IncidentTemplate]( [ID] [int] IDENTITY(1, 1) NOT NULL, [alarmtype] [int] NULL, [content] [nvarchar](2000) NULL, CONSTRAINT [PK_INCIDENTTEMPLATE] PRIMARY KEY CLUSTERED([ID]) ) EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘案件模板‘ ,@level0type=N‘SCHEMA‘, @level0name=N‘dbo‘, @level1type=N‘TABLE‘, @level1name=N‘IncidentTemplate‘ EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘序号‘ ,@level0type=N‘SCHEMA‘, @level0name=N‘dbo‘, @level1type=N‘TABLE‘, @level1name=N‘IncidentTemplate‘, @level2type=N‘COLUMN‘, @level2name=N‘ID‘ EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘案件性质‘ ,@level0type=N‘SCHEMA‘, @level0name=N‘dbo‘, @level1type=N‘TABLE‘, @level1name=N‘IncidentTemplate‘, @level2type=N‘COLUMN‘, @level2name=N‘alarmtype‘ EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘模板内容‘ ,@level0type=N‘SCHEMA‘, @level0name=N‘dbo‘, @level1type=N‘TABLE‘, @level1name=N‘IncidentTemplate‘, @level2type=N‘COLUMN‘, @level2name=N‘content‘</createsql> <columns> <column col_name="ID" col_id="1" col_typename="int" col_len="4" col_prec="" col_scale="" col_basetypename="int" col_defname="" col_rulname="" col_null="False" col_identity="True" col_flags="4" col_seed="1" col_increment="1" col_dridefname="" text="" col_iscomputed="0" text1="" col_NotForRepl="False" col_fulltext="False" col_AnsiPad="" col_DOwner="" col_DName="" col_ROwner="" col_RName="" collation="" ColType="" Column1="1" Column2="0" /> <column col_name="alarmtype" col_id="2" col_typename="int" col_len="4" col_prec="" col_scale="" col_basetypename="int" col_defname="" col_rulname="" col_null="True" col_identity="False" col_flags="0" col_seed="" col_increment="" col_dridefname="" text="" col_iscomputed="0" text1="" col_NotForRepl="False" col_fulltext="False" col_AnsiPad="" col_DOwner="" col_DName="" col_ROwner="" col_RName="" collation="" ColType="" Column1="1" Column2="0" /> <column col_name="content" col_id="3" col_typename="nvarchar" col_len="2000" col_prec="" col_scale="" col_basetypename="nvarchar" col_defname="" col_rulname="" col_null="True" col_identity="False" col_flags="1" col_seed="" col_increment="" col_dridefname="" text="" col_iscomputed="0" text1="" col_NotForRepl="False" col_fulltext="False" col_AnsiPad="" col_DOwner="" col_DName="" col_ROwner="" col_RName="" collation="Chinese_PRC_CI_AS" ColType="" Column1="1" Column2="0" /> </columns> <rows> <row> <cell columnname="ID">54</cell> <cell columnname="alarmtype">151</cell> <cell columnname="content"></cell> </row> <row> <cell columnname="ID">55</cell> <cell columnname="alarmtype">160</cell> <cell columnname="content"> <row> <cell columnname="ID">56</cell> <cell columnname="alarmtype">155</cell> <cell columnname="content"></cell> </row> <row> <cell columnname="ID">57</cell> <cell columnname="alarmtype">158</cell> <cell columnname="content"></cell> </row> <row> <cell columnname="ID">62</cell> <cell columnname="alarmtype">131</cell> <cell columnname="content"></cell> </row> <row> <cell columnname="ID">63</cell> <cell columnname="alarmtype">149</cell> <cell columnname="content"></cell> </row> <row> <cell columnname="ID">64</cell> <cell columnname="alarmtype">174</cell> <cell columnname="content"></cell> </row> </rows> </table> </tables> </database>
xml
时间: 2024-10-06 23:48:55