简体   繁体   中英

Write to end of XML with LINQ to XML

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM