Hello guys,
What i am trying to do is;
1- Check if xml file exist
If exist check if root element exist, if yes do nothing but if no exist then create root element
2- if xml doesnt exist create new xml file including root element
what am i doing wrong here ?
project file
http://rghost.net/50327047
Thanks in Advanced
What i am trying to do is;
1- Check if xml file exist
If exist check if root element exist, if yes do nothing but if no exist then create root element
2- if xml doesnt exist create new xml file including root element
what am i doing wrong here ?
Código: Seleccionar todo
namespace xml_test
{
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Test.xml";
public Form1()
{
InitializeComponent();
}
private void read()
{
try
{
XmlDocument xml = new XmlDocument();
xml.Load(path);
XmlNodeList people = xml.SelectNodes("//Person");
foreach (XmlNode person in people)
{
// ımageListBoxControl3.Items.Add(person.SelectSingleNode("Name").InnerText, 0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(path))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNode root = xmlDoc.SelectSingleNode("/root");
if (root == null)
{
XmlTextWriter xmlWriter = new XmlTextWriter(path, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("root");
xmlWriter.Close();
xmlDoc.Save(path);
read();
}
else
{
read();
}
}
else
{
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(path, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("root");
xmlWriter.Close();
xmlDoc.Save(path);
oku();
}
}
}
}
http://rghost.net/50327047
Thanks in Advanced