1.创建xml
public void CreateXml()
{
//创建一个XML文档对象
XmlDocument doc = new XmlDocument();
//声明XML头部信息
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
//添加进doc对象子节点
doc.AppendChild(dec);
//创建根节点
XmlElement root = doc.CreateElement("位置");
doc.AppendChild(root);
//再创建根节点下的子节点
XmlElement student = doc.CreateElement("attribute");
//设置子节点属性
student.SetAttribute("name","上下料");
//子节点下再创建标记
XmlElement one_X = doc.CreateElement("X");
//<X>的内容
XmlText xmlText1 = doc.CreateTextNode("21");//存储x的值
//将内容添加到<X>标记
one_X.AppendChild(xmlText1);
//再将<X>标记添加到<上下料>标记的子节点下
student.AppendChild(one_X);
XmlElement one_Y = doc.CreateElement("Y");
XmlText xmlText2 = doc.CreateTextNode("22");//存储y的值
one_Y.AppendChild(xmlText2);
student.AppendChild(one_Y);
XmlElement one_Z = doc.CreateElement("Z");
XmlText xmlText3 = doc.CreateTextNode("23");//存储z的值
one_Z.AppendChild(xmlText3);
student.AppendChild(one_Z);
//最后把标记添加到根节点的子节点下
root.AppendChild(student);
//doc文档对象保存写入
doc.Save("info.xml");
}
2.读取XML中存储的数据
public void readXml()
{
//将XML文件加载进来
XmlDocument doc = new XmlDocument();
doc.Load("info.xml");
//获取根节点
XmlElement root = doc.DocumentElement;
//获取子节点
XmlNodeList pnodes = root.GetElementsByTagName("attribute");
//使用foreach循环读出集合
foreach(XmlNode node in pnodes)
{
string name = ((XmlElement)node).GetAttribute("name");
string x = ((XmlElement)node).GetElementsByTagName("X")[0].InnerText;
string y = ((XmlElement)node).GetElementsByTagName("Y")[0].InnerText;
string z = ((XmlElement)node).GetElementsByTagName("Z")[0].InnerText;
Console.WriteLine("位置:{0},x:{1},y:{2},z:{3}", name, x, y, z);
}