Exemplo n.º 1
0
 static Book[] XmlDocumentDeserializer(string path)
 {
     XmlDocument doc = new XmlDocument();
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.IgnoreComments = true;
     XmlReader reader = XmlReader.Create(path, settings);
     doc.Load(reader);
     if(doc == null)
     {
         return null;
     }
     List<Book> bookList = new List<Book>();
     XmlNode xn = doc.SelectSingleNode("bookstore");
     XmlNodeList xnl = xn.ChildNodes;
     foreach(XmlNode _xn in xnl)
     {
         Book book = new Book();
         XmlElement xe = (XmlElement)_xn;
         book.Type = xe.GetAttribute("Type").ToString();
         book.ISBN = xe.GetAttribute("ISBN").ToString();
         XmlNodeList _xnl = xe.ChildNodes;
         book.Name = _xnl.Item(0).InnerText;
         book.Author = _xnl.Item(1).InnerText;
         float price;
         if(float.TryParse(_xnl.Item(2).InnerText,out price))
         {
             book.Price = price;
         }
         bookList.Add(book);
     }
     return bookList.ToArray();
 }
Exemplo n.º 2
0
 static void Main(string[] args)
 {
     string pathname = "Book.xml";
     /*
     Book []books = XmlDocumentDeserializer(path);
     foreach(Book b in books)
     {
         Console.WriteLine(b.ToString());
     }
      * */
     Book book = new Book("必修课","123243242334","Computer","XXX",32.12f);
     AddNode(pathname, book);
 }
Exemplo n.º 3
0
 static void AddNode(string path,Book book)
 {
     XmlDocument doc = new XmlDocument();
     doc.Load(path);
     XmlNode root = doc.SelectSingleNode("bookstore");
     XmlElement node = doc.CreateElement("book");
     XmlAttribute typeAttribute = doc.CreateAttribute("Type");
     typeAttribute.InnerText = book.Type;
     XmlAttribute isbnAttribute = doc.CreateAttribute("ISBN");
     isbnAttribute.InnerText = book.ISBN;
     XmlElement nameElement = doc.CreateElement("name") ;
     nameElement.InnerText = book.Name;
     XmlElement authorElement = doc.CreateElement("author");
     authorElement.InnerText = book.Author;
     XmlElement priceElement = doc.CreateElement("price");
     priceElement.InnerText = book.Price.ToString();
     node.AppendChild(nameElement);
     node.AppendChild(authorElement);
     node.AppendChild(priceElement);
     node.SetAttributeNode(typeAttribute);
     node.SetAttributeNode(isbnAttribute);
     root.AppendChild(node);
     doc.Save("c:\\aa.xml");
 }