XML操作
读写操作xml 3种方法 第一种略
读2
//实例化文档对象 版本信息 根元素
XmlDocument xml = new XmlDocument();
XmlDeclaration xel = xml.CreateXmlDeclaration("1.0", "utf-8", null);
xml.InsertBefore(xel, xml.DocumentElement);//版本信息放入跟元素前面
XmlElement root = xml.CreateElement("T"); //实例化一级子节点
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
XmlElement t =xml.CreateElement("TT");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
XmlElement tt =xml.CreateElement(ds.Tables[0].Columns[j].ToString());
tt.InnerText = ds.Tables[0].Rows[i][j].ToString();
t.AppendChild(tt);
}
root.AppendChild(t);
}
xml.AppendChild(root);
xml.Save(Path.Combine(Application.StartupPath, "xxxx.xml"));
MessageBox.Show("OK"); tt.InnerText = ds.Tables[0].Rows[i][j].ToString();
读取2
//定义对象
XmlDocument xml = new XmlDocument();
xml.Load(Path.Combine(Application.StartupPath, "xxx.xml"));
XmlNodeList xn = xml.SelectNodes("T/TT");
DataTable xmltable = new DataTable();
//定义表标题
foreach (XmlNode x in xn)
{
foreach (XmlNode xx in x.ChildNodes)
{
DataColumn col = new DataColumn(xx.Name.ToString());
xmltable.Columns.Add(col);
}
break;
}
foreach (XmlNode x in xn)
{
DataRow dr = xmltable.NewRow();
for (int i = 0; i < x.ChildNodes.Count; i++)
{
XmlNode xx = x.SelectSingleNode(xmltable.Columns[i].ToString());
dr[i] = xx.InnerText;
}
xmltable.Rows.Add(dr);
}
//得到对应节点
dataGridView1.DataSource = xmltable;
读2
//实例化文档对象 版本信息 根元素
XmlDocument xml = new XmlDocument();
XmlDeclaration xel = xml.CreateXmlDeclaration("1.0", "utf-8", null);
xml.InsertBefore(xel, xml.DocumentElement);//版本信息放入跟元素前面
XmlElement root = xml.CreateElement("T"); //实例化一级子节点
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
XmlElement t =xml.CreateElement("TT");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
XmlElement tt =xml.CreateElement(ds.Tables[0].Columns[j].ToString());
tt.InnerText = ds.Tables[0].Rows[i][j].ToString();
t.AppendChild(tt);
}
root.AppendChild(t);
}
xml.AppendChild(root);
xml.Save(Path.Combine(Application.StartupPath, "xxxx.xml"));
MessageBox.Show("OK"); tt.InnerText = ds.Tables[0].Rows[i][j].ToString();
读取2
//定义对象
XmlDocument xml = new XmlDocument();
xml.Load(Path.Combine(Application.StartupPath, "xxx.xml"));
XmlNodeList xn = xml.SelectNodes("T/TT");
DataTable xmltable = new DataTable();
//定义表标题
foreach (XmlNode x in xn)
{
foreach (XmlNode xx in x.ChildNodes)
{
DataColumn col = new DataColumn(xx.Name.ToString());
xmltable.Columns.Add(col);
}
break;
}
foreach (XmlNode x in xn)
{
DataRow dr = xmltable.NewRow();
for (int i = 0; i < x.ChildNodes.Count; i++)
{
XmlNode xx = x.SelectSingleNode(xmltable.Columns[i].ToString());
dr[i] = xx.InnerText;
}
xmltable.Rows.Add(dr);
}
//得到对应节点
dataGridView1.DataSource = xmltable;