Reputation:
I'm using the following code to write an XML file to disk. If I change the values for each field and re-run the code, the values saved will simply be replaced.
I've looked around here but I see no way to automatically append the new values to the end of the file as a new element and not simply replace everything.
XNamespace empNM = "urn:lst-emp:emp";
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(empNM + "Employees",
new XElement("Employee",
new XComment("Only 3 elements for demo purposes"),
new XElement("EmpId", "5"),
new XElement("Name", "Kimmy"),
new XElement("Sex", "Female")
)));
StringWriter sw = new StringWriter();
XmlWriter xWrite = XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
// Save to Disk
xDoc.Save("C:\\tempFolder\\test.xml");
Console.WriteLine("Saved");
Also, could someone please explain what "urn:lst-emp:emp";
in the first line does.
Upvotes: 0
Views: 125
Reputation: 3188
void Main()
{
XNamespace empNM = "urn:lst-emp:emp";
XDocument xDoc ;
string path="C:\\tempFolder\\test.xml";
if(!File.Exists(path))
{
xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(empNM + "Employees")
);
}
else
{
xDoc=XDocument.Load(path);
}
var element=new XElement("Employee",
new XComment("Only 3 elements for demo purposes"),
new XElement("EmpId", "5"),
new XElement("Name", "Kimmy"),
new XElement("Sex", "Female"));
xDoc.Element(empNM+"Employees").Add(element);
// Save to Disk
xDoc.Save(path);
Console.WriteLine("Saved");
}
Here is the Xml generated:
<?xml version="1.0" encoding="utf-16"?>
<Employees xmlns="urn:lst-emp:emp">
<Employee xmlns="">
<!--Only 3 elements for demo purposes-->
<EmpId>5</EmpId>
<Name>Kimmy</Name>
<Sex>Female</Sex>
</Employee>
<Employee xmlns="">
<!--Only 3 elements for demo purposes-->
<EmpId>5</EmpId>
<Name>Kimmy</Name>
<Sex>Female</Sex>
</Employee>
</Employees>
Upvotes: 1