using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//下面两个命名空间需要添加
using System.IO;
using System.Xml;
namespace CheckXML
{
public partial class Form1 : Form
{
string path;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDeclaration xmldecl;
//加载编码否则出现乱码现象
xmldecl = XmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlDoc.AppendChild(xmldecl);
XmlElement XmlE = XmlDoc.CreateElement("Father");
XmlE.SetAttribute("Name", "父亲");
XmlDoc.AppendChild(XmlE);
//创建具有父-子-孙的一个Xml文档形式,子节点数由外部textBox1输入,孙结点外部textBox2输入
for (int i = 0; i < Convert.ToInt32(textBox1.Text); i++)
{
XmlElement XmlEE = XmlDoc.CreateElement("Son" + i.ToString());
XmlEE.SetAttribute("Name" + i.ToString(), "儿子" + i.ToString());
XmlE.AppendChild(XmlEE);
for (int k = 0; k < Convert.ToInt32(textBox2.Text); k++)
{
XmlElement XmlEEE = XmlDoc.CreateElement("Son" + i.ToString() + k.ToString());
XmlEEE.SetAttribute("Name" + i.ToString(), "孙子" + i.ToString());
XmlEE.AppendChild(XmlEEE);
}
}
XmlDoc.Save(path);
}
private void button2_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
richTextBox1.LoadFile(path, RichTextBoxStreamType.PlainText);
}
private void Form1_Load(object sender, EventArgs e)
{
//设置xml文件的产生及保存路径
path = Application.StartupPath + "//Excise.xml";
//xml文件不存在时则创建
if (!File.Exists(path))
{
File.Create(path);
}
else
{
//存在的时候直接加载其中的内容
richTextBox1.LoadFile(path, RichTextBoxStreamType.PlainText);
////////////下面几行为删除欲操作xml文件的所有内容,之所以先显示后删除时为了创建后对比的需要
XmlDocument XmlDoc = new XmlDocument();
//将欲操作xml文档实体加载到xml类中
XmlDoc.Load(path);
//移除其中的所有内容
XmlDoc.RemoveAll();
//为了避免报错,载入一个子节点,和文档属性
XmlDeclaration xmlDer = XmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlDoc.AppendChild(xmlDer);
XmlElement XmlE = XmlDoc.CreateElement("Noting");
XmlDoc.AppendChild(XmlE);
//返回保存
XmlDoc.Save(path);
}
}
}
}
界面如下: