两种方法:using System;
using System.Xml; string sFileName = "book.xml";
XmlDocument myDocument = new XmlDocument();
myDocument.Load(sFileName);//方法1
XmlNode node= myDocument.DocumentElement.SelectSingleNode("book");
XmlNode node2 = node.CloneNode(true);
node2["price"].InnerText = "32.12";
node2.Attributes["genre"].Value = "书名";
node2.Attributes["publicationdate"].Value = "日期";
myDocument.DocumentElement.AppendChild(node2);

//方法2 XmlElement book = myDocument.CreateElement("book");
XmlAttribute genre = myDocument.CreateAttribute("genre");
genre.Value = "书名";
book.Attributes.Append(genre);
XmlAttribute publicationdate = myDocument.CreateAttribute("publicationdate");
publicationdate.Value = "日期";
book.Attributes.Append(publicationdate); XmlElement title = myDocument.CreateElement("title");
title.InnerText = "Pride And Prejudice";
book.AppendChild(title); XmlElement author = myDocument.CreateElement("author");

XmlElement firstname = myDocument.CreateElement("first-name");
firstname.InnerText = "Jane";
author.AppendChild(firstname); XmlElement lastname = myDocument.CreateElement("last-name");
lastname.InnerText = "Austen";
author.AppendChild(lastname); book.AppendChild(author);

XmlElement price = myDocument.CreateElement("price");
price.InnerText = "32.12"; book.AppendChild(price);
myDocument.DocumentElement.AppendChild(book); myDocument.Save(sFileName);

解决方案 »

  1.   

    DataSet ds = new DataSet();
    ds.ReadXml("fileName");
    ds.Tables["books"].Rows.Add(new object[]{
    "书名","日期",
    "Pride and Prejudice",
    "Jane",
    "Austen",
    32.12});
    ds.WriteXml("fileName");
      

  2.   

    try
    {
    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(filepath);
    XmlElement newebook = xmldoc.CreateElement("book");
    newbook.SetAttribute("genre","书名");
    newbook.SetAttribute("publicationdate","日期");
    XmlElement newement = xmldoc.CreateElement("title");
    newement.InnerText = "Pride And Prejudice";
    newbook.AppendChild(newement);
    newement = xmldoc.CreateElement("first-name");
    newement.InnerText = "Jane";
    newbook.AppendChild(newement);newement = xmldoc.CreateElement("last-name");
    newement.InnerText = "last-name" ;
    newbook.AppendChild(newement);newement = xmldoc.CreateElement("price");
    newement.InnerText = "32.12";
    newbook.AppendChild(newement);xmldoc.DocumentElement.AppendChild(newbook);
    XmlTextWriter myWriter = new XmlTextWriter(filepath,System.Text.Encoding.GetEncoding("gb2312"));
    myWriter.Formatting = Formatting.Indented;
    xmldoc.WriteContentTo(myWriter);
    myWriter.Close();
    }