将新节点添加到现有 XmlDocument 对象

本文关键字:XmlDocument 对象 添加 新节点 节点 | 更新日期: 2023-09-27 17:56:06

我有一个以下格式的xml。

<BOOKS>
    <BOOK>
        <TITLE>book 1</TITLE>
        <AUTHOR>author 1</AUTHOR>       
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </BOOK>
    <BOOK>
        <TITLE>book 2</TITLE>
        <AUTHOR>author 2</AUTHOR>       
        <PRICE>20.90</PRICE>
        <YEAR>1995</YEAR>
    </BOOK>
</BOOKS>

我有一个Add(XmlDocument xDoc, Book newBook)的方法,可以将新书添加到传递给Add(..)方法的XmlDocument对象。我该怎么做。

将新节点添加到现有 XmlDocument 对象

XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
XmlElement foo = doc.CreateElement("foo");
XmlElement bar = doc.CreateElement("bar");
bar.InnerText = "whatever";
foo.AppendChild(bar);
doc.DocumentElement.AppendChild(foo);
doc.Save("file.xml");

请参阅 Martin Honnen 帖子:向现有 XML 文档添加新节点