It look like this:
[XmlRoot("Library")]
public class LibraryModel
{
[XmlElement("Book")]
public List<BookModel> Books { get; set; }
}
and
public class BookModel
{
[XmlElement(ElementName = "Title")]
public string Title { get; set; }
[XmlElement(ElementName = "Author")]
public string Author { get; set; }
[XmlElement(ElementName = "ISBN")]
public string ISBN { get; set; }
}
Sample XML:
<?xml version="1.0" encoding="UTF-8"?>
<Library>
<Book>
<Title>The Name of the Wind</Title>
<Author>Patrick Rothfuss</Author>
<ISBN>9788580410631</ISBN>
</Book>
<Book>
<Title>The Wise Mans Fear</Title>
<Author>Patrick Rothfuss</Author>
<ISBN>9788834717790</ISBN>
</Book>
</Library>
My input is a BookModel book. I don't know if it's best to have it like BookModel book, or string title, string author, string ISBN:
BookModel book = new BookModel();
book.Title = "New title";
book.Author = "New author";
book.ISBN = "97839839033";
So my question is, how do I put a new bok (BookModel) to the XML file, at the end but inside the XMLRoot? And the class is gonna change type from BookModel to Book.
Expected result:
<?xml version="1.0" encoding="UTF-8"?>
<Library>
<Book>
<Title>The Name of the Wind</Title>
<Author>Patrick Rothfuss</Author>
<ISBN>9788580410631</ISBN>
</Book>
<Book>
<Title>The Wise Mans Fear</Title>
<Author>Patrick Rothfuss</Author>
<ISBN>9788834717790</ISBN>
</Book>
<Book>
<Title>New title</Title>
<Author>New author</Author>
<ISBN>97839839033</ISBN>
</Book>
</Library>
First of all, we need to convert our
class
toXML
like this:After that, we can do it this way:
Finally, this is the result after running this code: