日期:2014-05-20 浏览次数:20825 次
/// <summary> /// 1、创建BookStore.xml的XML文件,由函数CreateXmlFile()完成 /// </summary> /// <param name="xmlpath">XML文件的路径</param> private static void CreateXmlFile(string xmlpath) { XDocument doc = new XDocument( ///创建XDocument类的实例 new XDeclaration("1.0", "utf-8", "yes"),///XML的声明,包括版本,编码,xml文件是否独立 new XElement("Books", ///添加根节点 new XElement("Book", ///添加一个节点 new XAttribute("BookID", "001"),///添加属性BookID new XElement("BookNo", "0001"), ///添加元素BookNo new XElement("BookName", "Book 0001"),///添加元素BookName new XElement("BookPrice", "40"),///添加元素BookPrice new XElement("BookRemark", "This is a book 0001")///添加元素BookRemark ) ) ); ///保存XML文件到指定地址 doc.Save(xmlpath); Console.WriteLine(doc); } //调用函数CreateXmlFile(string xmlpath) static void Main(string[] args) { ///创建一个名为BookStore.xml的xml文件 Program.CreateXmlFile(@"C:\BookStore.xml"); }
/// <summary> /// 2、添加元素 /// </summary> /// <param name="xmlpath">XML文件的路径</param> private static void AddXmlElement(string xmlpath) { ///导入XML文件 XElement xe = XElement.Load(xmlpath); ///创建一个新节点 XElement book1 = new XElement("Book", new XAttribute("BookID", "002"), new XElement("BookNo", "0002"), new XElement("BookName", "Book 0002"), new XElement("BookPrice", "50"), new XElement("BookRemark", "This is a book 0002") ); ///添加节点到XML文件中,并保存 xe.Add(book1); ///创建一个新节点 XElement book2 = new XElement("Book", new XAttribute("BookID", "003"), new XElement("BookNo", "0003"), new XElement("BookName", "Book 0003"), new XElement("BookPrice", "30"), new XElement("BookRemark", "This is a book 0003") ); ///添加节点到XML文件中,并保存 xe.Add(book2); ///创建一个新节点 XElement book3 = new XElement("Book", new XAttribute("BookID", "004"), new XElement("BookNo", "0004"), new XElement("BookName", "Book 0004"), new XElement("BookPrice", "60"), new XElement("BookRemark", "This is a book 0004") ); ///添加节点到XML文件中 xe.Add(book3); ///保存到XML文件中 xe.Save(xmlpath); Console.WriteLine(xe); } //调用函数AddXmlElement(string xmlpath) ///添加XML元素 Program.AddXmlElement(@"C:\BookStore.xml");