XML文件转成DataTable - XmlToDataTable
2015-11-17 12:19:55 访问(1653) 赞(0) 踩(0)
/*
XML文件
<?xml version="1.0" encoding="gb2312"?>
<Ftps>
<Item url="1" DataColumnIndex="1" DataColumnName="VID" />
<Item url="2" DataColumnIndex="2" DataColumnName="User_ID" />
</Ftps>
*/
/// <summary>
/// XML文件转成DataTable
/// </summary>
/// <param name="fileName"></param>
/// <param name="rootKey"></param>
/// <returns></returns>
public DataTable XmlToDataTable
(
string fileName,
string rootKey
)
{
if (fileName == null || fileName.Length == 0)
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ "传入的字符串参数:"
+ "string fileName"
+ "为null或为空。"
);
}
if (!File.Exists(fileName))
{
throw new Exception
(
"方法:"
+ MethodBase.GetCurrentMethod().ReflectedType.FullName
+ " "
+ MethodBase.GetCurrentMethod().ToString()
+ " 发生异常:"
+ fileName + "文件不存在。"
);
}
XmlDocument xmlDoc = null;
XmlElement root = null;
DataTable theResult = null;
try
{
xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlNodeList xnl = null;
root = xmlDoc.DocumentElement;
if (root == null)
return null;
if (root.Name == rootKey)
{
xnl = root.ChildNodes;
}
else
{
foreach (XmlNode nodeOne in root.ChildNodes)
{
if (nodeOne.Name == rootKey)
{
xnl = nodeOne.ChildNodes;
break;
}
}
}
if (xnl == null)
return null;
theResult = new DataTable();
DataRow dr = null;
foreach (XmlNode xn in xnl)
{
dr = theResult.NewRow();
theResult.Rows.Add(dr);
foreach (XmlAttribute xmlAttri in xn.Attributes)
{
if (xmlAttri == null)
continue;
if (!theResult.Columns.Contains(xmlAttri.Name))
theResult.Columns.Add(new DataColumn(xmlAttri.Name));
if(xmlAttri.Value==null)
dr[xmlAttri.Name] = DBNull.Value;
else
dr[xmlAttri.Name] = xmlAttri.Value;
}
}
}
catch (Exception err)
{
throw err;
}
finally
{
root = null;
xmlDoc = null;
}
return theResult;
}
标签:
XML文件转成DataTable - XmlToDataTable 


上一条:
下一条:
相关评论
发表评论