Ilan
Ilan

Reputation: 513

Adding and removing XDocument elements and their childs with LINQ

I've been coding a program that uses XDocument to write XML files. The structure of the test program is:

<SchoolData storeName="mikveIsrael" location="mikve">
    <employee id="1">
        <personalInfo>
            <name>Ilan Berlinbluv</name>
            <zip>58505</zip>
        </personalInfo>
        <employeeInfo>
            <salary>5000</salary>
            <id>1</id>
        </employeeInfo>
    </employee>
    <employee id="2">
        <personalInfo>
            <name>Noam Inbar</name>
            <zip>58504</zip>
        </personalInfo>
        <employeeInfo>
            <salary>4500</salary>
            <id>2</id>
        </employeeInfo>
    </employee>
    <employee id="3">
        <personalInfo>
            <name>Adi Raiten</name>
            <zip>58503</zip>
            </personalInfo>
        <employeeInfo>
            <salary>5000</salary>
            <id>3</id>
        </employeeInfo>
    </employee>
</SchoolData>

So far, my test program writes that to Employee.xml on my desktop. I can also read the data from XML using XDocument.Load(), and parse different information. However I don't know how to add or remove elements (the element I want to add is <employee>, which contains all the elements such as name and such. Can someone point me in the right direction on how this is done?

Upvotes: 0

Views: 554

Answers (1)

pescolino
pescolino

Reputation: 3123

Adding elements to XML is pretty straightforward. Using the right indentation you can even see the XML structure in your code:

XDocument doc = XDocument.Load(fileName);

doc.Root.Add(new XElement("employee", new XAttribute("id", 42),
                 new XElement("personalInfo",
                     new XElement("name", "Arthur Dent"),
                     new XElement("zip", "00000")),
                 new XElement("employeeInfo",
                     new XElement("salary", 0),
                     new XElement("id", 3))));

doc.Save(fileName);

Upvotes: 2

Related Questions