Hi my aim is to allow the xml file to write a new xml document if it does not exist and if it does exist then add elements to the xml file. The issue is that if gives me an error saying “xwriter does not exist in the current context” after the else if() statement. Thanx
so far i have tried this but its not working.
private void button1(object sender, EventArgs e)
{
if (!File.Exists("doc.xml"))
{
XmlTextWriter xwriter = new XmlTextWriter("doc.xml", Encoding.UTF8);
XmlWriterSettings settings = new XmlWriterSettings();
}
else if (File.Exists("doc.xml"))
{
xwriter.Formatting = Formatting.Indented;
xwriter.WriteStartDocument();
xwriter.WriteStartElement("myCourse");
xwriter.WriteString("Test");
xwriter.WriteEndElement();
}
}
You have two primary problems
1) Your
elsestatement tries to use a variable that is declared and created in theifstatement. That is, xwriter simply does not exist in theelse, because it is localised to the scope of theifbranch of the code. To use it in theelsestatement as well, it must be declared before theifstatement, so that it is available to both theifandelsebranches of the code.2) You can’t append to an XML file. If you create the xwriter outside the
ifstatement, the code will compile and run, but yourelseblock of code will simply overwrite the existing contents of the xml file.To append to xml as you desire you need to open the file, seek to the location where the end tag of the root/document element starts, and then write using an xml writer so that it overwrites the end tag and forms new, valid xml. To close the file you must then append raw text that adds a new end tag for the root/document element so that the xml file remains valid.
Another (less efficient) approach is to load the XML from the file, and then rewrite the existing contents as well as the new data.
(You also don’t need to check the existence of the file twice)