Greetings,
I am new to C# and XML coding. I have read a few tutorials online about how to deal with XML files. Currently I have a setup that creates an XML file with a few products that are being saved. I would like to read the file that has already been created, add another product to it and then save it but currently my code only overwrites what I have. Does anyone know of the way to add on to an XML file when trying to write to it. Here's the example of my XML file.
<table>
-<part>
<product_name>Test</product_name>
<length>10</length> <width>8</width>
<thickness>1.5</thickness>
<offset>.25</offset>
<yelements>6</yelements>
<xelements>7</xelements>
</part>
</table>
Here's the code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("product.xml");
XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.WriteStartElement("Table");
createNode(Name.Text, Cut_Area_X.Text, Cut_Area_Y.Text, Thickness.Text, Offset.Text, Number_Cuts_X.Text, Number_Cuts_Y.Text, writer);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
MessageBox.Show("XML File created ! ");
}
private void createNode(string Name, string Length, string Width, string Thickness, string offset, string YElements, string XElements, XmlTextWriter writer)
{
writer.WriteStartElement("Part");
writer.WriteStartElement("Product_Name");
writer.WriteString(Name);
writer.WriteEndElement();
writer.WriteStartElement("Length");
writer.WriteString(Length);
writer.WriteEndElement();
writer.WriteStartElement("Width");
writer.WriteString(Width);
writer.WriteEndElement();
writer.WriteStartElement("Thickness");
writer.WriteString(Thickness);
writer.WriteEndElement();
writer.WriteStartElement("Offset");
writer.WriteString(offset);
writer.WriteEndElement();
writer.WriteStartElement("YElements");
writer.WriteString(YElements);
writer.WriteEndElement();
writer.WriteStartElement("XElements");
writer.WriteString(XElements);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}