1、示例
<?xml version="1.0" encoding="utf-8" standalone="no"?><DATA><ITEMS><ITEM><ID>01<ID/><CODE>0001<CODE><NAME>测试1<NAME/></ITEM><ITEM><ID>02<ID/><CODE>0002<CODE><NAME>测试2<NAME/></ITEM></ITEMS></DATA>
2、用DataTable存储
private DataTable GetDataTable(string xmlStr, string nodepath)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
XmlNodeList xlist = doc.GetElementsByTagName(nodepath);
DataTable Dt = new DataTable();
DataRow Dr;
for (int i = 0; i < xlist.Count; i++)
{
Dr = Dt.NewRow();
XmlElement xe = (XmlElement)xlist.Item(i);
for (int j = 0; j < xe.Attributes.Count; j++)
{
if (!Dt.Columns.Contains(xe.Attributes[j].Name))
Dt.Columns.Add(xe.Attributes[j].Name);
Dr[xe.Attributes[j].Name] = xe.Attributes[j].Value;
}
for (int j = 0; j < xe.ChildNodes.Count; j++)
{
if (!Dt.Columns.Contains(xe.ChildNodes.Item(j).Name))
Dt.Columns.Add(xe.ChildNodes.Item(j).Name);
Dr[xe.ChildNodes.Item(j).Name] = xe.ChildNodes.Item(j).InnerText;
}
Dt.Rows.Add(Dr);
}
return Dt;
}
3、解析
string xmlfile="xml路径";
XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);
string xmlData = doc.InnerXml;
DataTable table = GetDataTable(xmlData, "//ITEM");
if (table != null && table.Rows.Count > 0)
{
for (int i = 0; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
string id = row["ID"].ToString();
string code= row["CODE"].ToString();
string name= row["NAME"].ToString();
//将数据逐条存入数据库
//具体的存储方式根据实际情况编写代码
}
}