Develop a Windows
Forms application that does following:
1. Reads the sample .xml file (given
above) and displays its contents in a Label control.
2. Displays all the titles (for books) in
a ListBox control.
. Deletes the book for the selected title
from the ListBox. (use a delete button)
4. Append a complete book element to the
.xml file (use text boxes to enter values)
Sample XML File
<?xml version="1.0"?>
<bookstore>
<book>
<title>World History</title>
<publisher>MSPress</publisher>
<authors>
<author>Carson</author>
</authors>
</book>
<book>
<title>C++ for Dummies</title>
<publisher>Prentice Hall</publisher>
<authors>
<author>A. Levine</author>
<author>B. Levine</author>
</authors>
</book>
<book>
<title>Cooking Tips</title>
<publisher>Anaar Kali Publishers</publisher>
<authors>
<author>Shaista Alam</author>
</authors>
</book>
</bookstore>
Code
using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using System.Text;
using
System.Windows.Forms;
using
System.Xml;
namespace lab09vp
{
public partial class Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
XmlDocument
doc;
XmlNodeList
n_list;
private
void load()
{
tb_del.Items.Clear();
doc = new
XmlDocument();
doc.Load("c:\\lab9.xml");
string
content = doc.OuterXml;
content = content.Replace("><", ">\n<");
lb_load.Text = content;
n_list = doc.GetElementsByTagName("title");
for
(int i = 0; i <
doc.DocumentElement.ChildNodes.Count; i++)
{
tb_del.Items.Add(n_list[i].InnerText);
}
}
private
void Form1_Load(object
sender, EventArgs e)
{
load();
}
private
void btn_del_Click(object
sender, EventArgs e)
{
XmlNode
node_to_del= n_list[tb_del.SelectedIndex].ParentNode;
XmlNode
root= doc.DocumentElement;
root.RemoveChild(node_to_del);
doc.Save("c:\\lab9.xml");
load();
}
private
void btn_append_Click(object
sender, EventArgs e)
{
XmlElement
add_element = doc.CreateElement("book");
XmlElement
ele_title = doc.CreateElement("title");
ele_title.InnerText =
textBox1.Text;
XmlElement
ele_publisher = doc.CreateElement("publisher");
ele_publisher.InnerText =
textBox2.Text;
XmlElement
ele_author = doc.CreateElement("author");
ele_author.InnerText =
textBox3.Text;
XmlElement
authors = doc.CreateElement("authors");
authors.AppendChild(ele_author);
add_element.AppendChild(ele_title);
add_element.AppendChild(ele_publisher);
add_element.AppendChild(authors);
doc.DocumentElement.AppendChild(add_element);
doc.Save("c:\\lab9.xml");
load();
}
}
}
Screen Shot
No comments:
Post a Comment