0

它看起来像这样:

[XmlRoot("Library")]
    public class LibraryModel
    {
        [XmlElement("Book")]
        public List<BookModel> Books { get; set; }
    }

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; }
    }

示例 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>

我的输入是 BookModel 书。不知道最好有BookModel book之类的,还是字符串title、字符串作者、字符串ISBN:

BookModel book = new BookModel();
book.Title = "New title";
book.Author = "New author";
book.ISBN = "97839839033";

所以我的问题是,如何将新书(BookModel)放入 XML 文件,最后但在 XMLRoot 中?该课程将从 BookModel 更改为 Book 类型。

预期结果:

<?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>
4

1 回答 1

0

首先,我们需要像这样转换我们classXML

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;
}

之后,我们可以这样做:

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");

最后,这是运行这段代码后的结果:

<?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>
于 2020-12-02T15:34:05.600 回答