0

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>
Henry Boo
  • 11
  • 3
  • can you please give an example of what your xml should look like? – MakePeaceGreatAgain Dec 02 '20 at 14:08
  • @HimBromBeere The file look like this: - - The Name of the Wind Patrick Rothfuss 9788580410631 The Wise Mans Fear Patrick Rothfuss 9788834717790 So I want to add a new book between and at the end – Henry Boo Dec 02 '20 at 14:20
  • please add that into your question. It´s nearly impossible to read it from the comments. Also add how what input you have and the expected result. – MakePeaceGreatAgain Dec 02 '20 at 14:24
  • @HimBromBeere I have updated it now – Henry Boo Dec 02 '20 at 14:42
  • add the new book to your library: `myLibraray.Books.Add(newBook)`. Or is your question actually "how to update an existing (xml-)file"? – MakePeaceGreatAgain Dec 02 '20 at 14:44
  • @HimBromBeere Oh ok! Should I add the new book after some deserialization or is it enough to just add it? I'm not so good at this – Henry Boo Dec 02 '20 at 14:48
  • sure, you first have to read (=de-serialize) your existing file, then perform your changes on that de-serialzed data, and wright the data back (=serialize). – MakePeaceGreatAgain Dec 02 '20 at 14:50
  • @HimBromBeere Yes, my question was how to update my existing (xml-)file. The deserialize part works good but not the serialize part. Do you recomend a xmlwriter, a stringwriter or something else? – Henry Boo Dec 02 '20 at 15:09
  • You are missing : Books.Add(Book); – jdweng Dec 02 '20 at 15:12

1 Answers1

0

First of all, we need to convert our class to XML like this:

public string BookModelToXml(object obj)
{
    XmlDocument doc = new XmlDocument();
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");

    using (XmlWriter writer = doc.CreateNavigator().AppendChild())
    {
        new XmlSerializer(obj.GetType()).Serialize(writer, obj, ns);
    }

    string className = obj.GetType().Name;
    return doc[className].InnerXml;
}

After that, we can do it this way:

BookModel bookModel = new BookModel() { Author = "New Author", Title = "New Title", ISBN = "New ISBN" };

XmlDocument doc = new XmlDocument();
doc.Load("Your path");
XmlNode root = doc.DocumentElement;
XmlNode xmlNode = doc.CreateElement("Book");
xmlNode.InnerXml = BookModelToXml(bookModel);
root.AppendChild(xmlNode);
doc.Save("Your path");

Finally, this is the result after running this code:

<?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>
  <Book>
    <Title>Added Title</Title>
    <Author>Added Author</Author>
    <ISBN>Added ISBN</ISBN>
  </Book>
</Library>
Saeid Amini
  • 1,313
  • 5
  • 16
  • 26
  • Thank you! Should I change the ["BookModel"] to something else in the last row of your codepart (return doc["BookModel"].InnerXml;)? . When I run this code I get stuck and I get a System.NullReferenceException. – Henry Boo Dec 02 '20 at 16:10
  • It depends on the class name that we are converting to XML. In this case, we are converting the object `bookModel` of class `BookModel`. – Saeid Amini Dec 02 '20 at 16:21
  • Ok so du you know how I can fix that? – Henry Boo Dec 02 '20 at 16:45
  • I edited my answer. Take a look at the differences [here](https://stackoverflow.com/posts/65111213/revisions) – Saeid Amini Dec 02 '20 at 17:02
  • And also you can change `public string BookModelToXml(BookModel obj)` to `public string BookModelToXml(object obj)`. Now it works for any class. – Saeid Amini Dec 02 '20 at 17:07
  • Thank you so much, it works just fine now! Is it ok to ask you something else? I'm working on a MVC-project and I have some more problems – Henry Boo Dec 02 '20 at 18:08
  • Sure. If you have a new question, please ask it by clicking the [Ask Question button](https://stackoverflow.com/questions/ask) – Saeid Amini Dec 02 '20 at 18:21
  • Please do not add a comment on your question or on an answer to say "Thank you". Comments are meant for requesting clarification, leaving constructive criticism, or adding relevant but minor additional information – not for socializing. If you want to say "thank you," vote on or accept that person's answer. [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Saeid Amini Dec 02 '20 at 18:30