Hi I’m making my own ToDo program, and I need to add the ability for the user to create a ToDo item. When they do this, I need to be able to add in an XML element/section in a list file.
My XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<list>
<item>
<name>Item 1</name>
<due>Tomorrow</due>
</item>
<item>
<name>Item 2</name>
<due>Thursday</due>
</item>
</list>
Say if a user created an item with the name ‘papers’ and due date ‘Tomorrow’, I need to be able to make another list element like above and insert it before the </list> tag.
Basically I’m asking how can I write to my XML file at a specific position (at the end before the </list> tag)? Is it possible just to go to the end of the file and go back a line?
Sure it is, but it would be very unsafe to do so. It makes an assumption about how the XML file is written, this is also equally valid XML:
Now it would be getting a little more complicated. Instead, you should use an XML parser, parse the XML file, manipulate the XML’s Document Object Model (DOM), and save it back. You could do that like so:
This makes use of the Framework’s
XDocumentclass, which is a good tool to easily work with an XML file’s object model.You can use LINQ-to-XML to write queries for deleting. Simply write a LINQ query to select the elements you want, and use
Remove(). Here is an example that removes the item we just added: