Reputation: 21
Say I have an XML Document that looks like this:
<BOOK>
<NAME>Home</NAME>
<ISBN>0-943396-04-2</ISBN>
<PRICE>$0.82</PRICE>
</BOOK>
And I have a program that has the purpose of allowing the user to add another book to the list... what code would I put on the Button I have titled "Add Book" to make it add another set of information?
So the end product would look like this:
<BOOK>
<NAME>Home</NAME>
<ISBN>0-943396-04-2</ISBN>
<PRICE>$0.82</PRICE>
</BOOK>
<BOOK>
<NAME>Work</NAME>
<ISBN>0-85131-041-9</ISBN>
<PRICE>$0.99</PRICE>
</BOOK>
I am using Microsoft Visual C# 2010 Express, if that helps.
Upvotes: 2
Views: 364
Reputation: 2801
firstly youll need to put a container around your books list so
<BOOKS>
<BOOK>
<NAME>Home</NAME>
<ISBN>0-943396-04-2</ISBN>
<PRICE>$0.82</PRICE>
</BOOK>
</BOOKS>
Then you'll need to parse it with something are you storing it in a file? if so then
XElement.Load(filename);
otherwise you can parse a string
XElement el = XElement.Parse(@"<BOOKS><BOOK>
<NAME>Home</NAME>
<ISBN>0-943396-04-2</ISBN>
<PRICE>$0.82</PRICE>
</BOOK></BOOKS>");
then create a and add a new book
var newBook = new XElement("BOOK", new[]
{
new XElement("NAME", "thename"),
new XElement("ISBN", "isbn"),
new XElement("PRICE", ".71")
});
el.Add(newBook);
and save it if you need to
el.Save(filename)
Reformatted comment below;
var el = XElement.Load("Ops.xml");
var newOp = new XElement("Operation", new[] {
new XElement("Operation Name", textBox2.Text),
new XElement("Operation Date", dateTimePicker1.Value)
});
el.Add(newOp);
Upvotes: 2