Search code examples
c#xmlwindows-phone-7records

Adding data to XML file


My XML file is:

<?xml version="1.0" encoding="utf-8" ?>
<people>
<person
index="1"
name="Zlecenie numer jeden"
beneficiary="Kowalski"
description="Proste zlecenie jakiejs strony czy cos"
price="800"
deadline="27.12.2013" />
</people>

How can I add to this existing file, something like new record:

<person
index="4"
name="Zlecenie numer cztery"
beneficiary="Kowalski"
description="Proste zlecenie jakiejs strony czy cos"
price="800"
deadline="27.12.2013" />

or remove or if you know how to update existing record then this too. Thanks


Solution

  • Try the next code snippet for adding element into xml. Note that I've used xml as string with escaped characters. You probably have xml file

    var str = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<people>\r\n<person\r\nindex=\"1\"\r\nname=\"Zlec" +
    "enie numer jeden\"\r\nbeneficiary=\"Kowalski\"\r\ndescription=\"Proste zlecenie jakiejs " +
    "strony czy cos\"\r\nprice=\"800\"\r\ndeadline=\"27.12.2013\" />\r\n</people>";
    
    var xml = XElement.Parse(str);
    var newNode = new XElement("person", 
                        new XAttribute("index", 4),
                        new XAttribute("name", "Zlecenie numer cztery"),
                        new XAttribute("beneficiary", "Kowalski"),
                        new XAttribute("description", "Proste zlecenie jakiejs strony czy cos"),
                        new XAttribute("price", 800),
                        new XAttribute("deadline", "27.12.2013"));
    
    xml.Add(newNode);
    
    //you can store whole xml tree in one variable simply by calling ToString on xml
    str = xml.Tostring();
    
    Console.WriteLine(str);
    

    Prints:

    <people>
      <person index="1" name="Zlecenie numer jeden" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
      <person index="4" name="Zlecenie numer cztery" beneficiary="Kowalski" description="Proste zlecenie jakiejs strony czy cos" price="800" deadline="27.12.2013" />
    </people>