السلام عليكم عند تطبيق هذا الكود لا يتم انشاء ملف xml و يطبع الخطأ التالي : "مستند XML غير صالح، ليس للمستند عنصر جذر.." عند السطر "doc.Save(PATH);"
ولكن اذا كان الملف منشأ مسبقا فإنه يتم تنفيذه بدون اخطاء .
مع العلم ان الكود يقوم بإختبار هل ملف xml موجود ام لا فإذا كان غير موجود فإنه يقوم بإنشاء ملف xml كقاعدة بيانات .
XmlDocument doc = new XmlDocument();
private void button1_Click(object sender, EventArgs e)
{
string str = txtID.Text.Trim();
double num;
bool isnum = double.TryParse(str, out num);
string str2 = txtmobile.Text.Trim();
double num2;
bool isnum2 = double.TryParse(str2, out num2);
if (isnum)
{
if (isnum2)
{
string sStartupPath = Application.StartupPath;
string PATH;
PATH = sStartupPath + "\\test.xml";
if (!System.IO.File.Exists(PATH))
{
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlElement employee = doc.CreateElement("Employee");
XmlElement data = doc.CreateElement("Data");
XmlAttribute nat = doc.CreateAttribute("nationality");
XmlAttribute id = doc.CreateAttribute("empl_id");
XmlAttribute comp = doc.CreateAttribute("company");
XmlAttribute mobile = doc.CreateAttribute("mobile");
data.InnerText = txtName.Text;
nat.Value = txtNationality.Text;
id.Value = txtID.Text;
comp.Value = txtcomp.Text;
mobile.Value = txtmobile.Text;
data.Attributes.Append(nat);
data.Attributes.Append(id);
data.Attributes.Append(comp);
data.Attributes.Append(mobile);
employee.AppendChild(data);
doc.Save(PATH);
MessageBox.Show("Name :\t\t" + txtName.Text +
"\nNationality :\t" + txtNationality.Text +
"\nEmployee Id :\t" + txtID.Text +
"\nCompany :\t" + txtcomp.Text +
"\nMobile :\t\t" + txtmobile.Text);
txtName.Text = "";
txtNationality.Text = "";
txtID.Text = "";
txtcomp.Text = "";
txtmobile.Text = "";
}
else
{
doc.Load(PATH);
XmlElement employee = doc.DocumentElement;
XmlElement data = doc.CreateElement("Data");
XmlAttribute nat = doc.CreateAttribute("nationality");
XmlAttribute id = doc.CreateAttribute("empl_id");
XmlAttribute comp = doc.CreateAttribute("company");
XmlAttribute mobile = doc.CreateAttribute("mobile");
data.InnerText = txtName.Text;
nat.Value = txtNationality.Text;
id.Value = txtID.Text;
comp.Value = txtcomp.Text;
mobile.Value = txtmobile.Text;
data.Attributes.Append(nat);
data.Attributes.Append(id);
data.Attributes.Append(comp);
data.Attributes.Append(mobile);
employee.AppendChild(data);
doc.Save(PATH);
MessageBox.Show("Name :\t\t" + txtName.Text +
"\nNationality :\t" + txtNationality.Text +
"\nEmployee Id :\t" + txtID.Text +
"\nCompany :\t" + txtcomp.Text +
"\nMobile :\t\t" + txtmobile.Text);
txtName.Text = "";
txtNationality.Text = "";
txtID.Text = "";
txtcomp.Text = "";
txtmobile.Text = "";
}
}