首先引入命名空间System.Xml;
声明对象:
public XmlDocument xmlDoc = null;
public XmlNode xmlNode=null;
public XmlElement xmlEle = null;
创建xml文件:
public void CreateXml(string xmlPath) {
try {
xmlDoc = new XmlDocument();
xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "version=1.0", "");
xmlDoc.AppendChild(xmlNode);
xmlEle = xmlDoc.CreateElement("Books");
xmlEle.SetAttribute("id","05020");
xmlEle.InnerText = "05020";
xmlDoc.AppendChild(xmlEle);
for(int i=0;i<9;i++)
{
XmlElement xmlEle2 = xmlDoc.CreateElement("SubBooks"+i);
xmlEle2.SetAttribute("id","05020"+i);
xmlEle2.InnerText = "abc";
xmlEle.AppendChild(xmlEle2);
}
}
catch (Exception e2) { throw new Exception(e2.Message); }
xmlDoc.Save(xmlPath);
}
| |
读取数据:
public void ReadXml(string xmlPath) {
xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
try {
XmlNode xmlNode = (XmlNode)xmlDoc.SelectSingleNode("Books");
XmlNodeList xnl = xmlNode.ChildNodes;
string msg = "";
foreach (XmlNode xn in xnl) {
//XmlElement xe = (XmlElement)xn;
msg+= xn.InnerText.ToString() + "/n/r";
}
MessageBox.Show(msg);
}
catch (Exception e2) { throw new Exception(e2.Message); }
}