//创建一个数据集,将其写入xml文件
string name = "1.xml";
System.Data.DataSet ds = new System.Data.DataSet("MESSAGE");
System.Data.DataTable table = new System.Data.DataTable("FeedBack");
ds.Tables.Add(table);
table.Columns.Add("Model_Name", typeof(string));
table.Columns.Add("PRJ_Name", typeof(string));
table.Columns.Add("area_name", typeof(string));
table.Columns.Add("Major_Name", typeof(string));
System.Data.DataRow row = table.NewRow();
row[] = Model_Name;
row[] = PRJ_Name;
row[] = area_name;
row[] = Major_Name;
ds.Tables["FeedBack"].Rows.Add(row);
string path = ("E:/BIM_APP/BIM_APP_ModelInsp/" + name);
ds.WriteXml(path);
这个方法只是针对临时存放的数据,多次向XML里面添加数据只会保存最后一次添加的数据,不是全部保存。
XML展示
<?xml version="1.0" standalone="yes"?>
<MESSAGE>
<FeedBack>
<Model_Name>name</Model_Name>
<PRJ_Name>test</PRJ_Name>
<area_name>test</area_name>
<Major_Name>test</Major_Name>
</FeedBack>
</MESSAGE>
读取XML数据
XmlDocument doc = new XmlDocument();
doc.Load("E:/BIM_APP/BIM_APP_ModelInsp/1.xml");
XmlElement xmlRoot = doc.DocumentElement;
foreach (XmlNode node in xmlRoot.ChildNodes)
{
label21.Text = node["Model_Name"].InnerText;
label23.Text = node["PRJ_Name"].InnerText;
label25.Text = node["area_name"].InnerText;
label26.Text = node["Major_Name"].InnerText;
}
删除方法
XmlDocument xdoc = new XmlDocument();
xdoc.Load("E:/BIM_APP/BIM_APP_ModelInsp/1.xml");
//获得元素列表
XmlElement xeXML = xdoc.DocumentElement;
//获得父节点数量
int nodeCount = xeXML.ChildNodes.Count;
for (int i = ; i < nodeCount; i++)
{
XmlNode root = xdoc.SelectSingleNode("MESSAGE");
root.RemoveChild(xeXML.ChildNodes[i]);
nodeCount = nodeCount - ;
xdoc.Save("E:/BIM_APP/BIM_APP_ModelInsp/1.xml");
}
nodeCount = nodeCount - ;
这种删除方法建议用在删除全部的数据上,MESSAGE就是XML的节点,删除这个节点下面全部的数据。
读取到指定的节点
XmlDocument xml = new XmlDocument();
xml.Load(strUrl); var selectItemList = new List<Translation>();
XDocument xdoc = XDocument.Load(strUrl);
XElement xroot = xdoc.Root;//根节点
var nodes = xroot.Descendants().FirstOrDefault(a => a.Name.LocalName == Nodes);//获取指定的XML节点 foreach (XElement e in nodes.Elements("Param"))
{
selectItemList.Add(new Translation() { Text = e.Value, Value = e.FirstAttribute.Value, Name = e.LastAttribute.Value });
}