Example of C Realizing Addition Deletion Modification and Search Function of XML Documents
- 2021-11-24 02:44:46
- OfStack
This paper describes the example of C # to achieve the function of adding, deleting, modifying and checking XML documents. Share it for your reference, as follows:
1. Create the instance XML file (Books. xml)
<?xml version="1.0" encoding="iso-8859-1"?>
<bookstore>
<book id="1" category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book id="2" category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book id="3" category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book id="4" category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
2. Create book information entity class (BookInfo. cs)
public class BookInfo
{
/// <summary>
/// Books ID
/// </summary>
public int BookId { set; get; }
/// <summary>
/// Book title
/// </summary>
public string Title { set; get; }
/// <summary>
/// Book classification
/// </summary>
public string Category { set; get; }
/// <summary>
/// Book language
/// </summary>
public string Language { set; get; }
/// <summary>
/// Book author
/// </summary>
public string Author { set; get; }
/// <summary>
/// Publication time
/// </summary>
public string Year { set; get; }
/// <summary>
/// Sales price
/// </summary>
public decimal Price { set; get; }
}
3. Create a library information business logic class (BookInfoBLL. cs)
using System.Xml; // Reference to related files
public class BookInfoBLL
{
private string _basePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/xml/Books.xml"; //XML File path
private XmlDocument _booksXmlDoc = null; // Create XML Document object
public BookInfoBLL()
{
try
{
_booksXmlDoc = new XmlDocument(); // Initialization XML Document object
_booksXmlDoc.Load(_basePath); // Loads the specified XML Document
}
catch (Exception ex)
{
throw new Exception(" Loading XML Error in document: " + ex.Message);
}
}
/// <summary>
/// Get a list of books ( Check )
/// </summary>
/// <param name="param"> Parametric condition </param>
/// <returns> Book list </returns>
public List<BookInfo> GetBookInfoList(BookInfo param)
{
List<BookInfo> bookInfoList = new List<BookInfo>();
string xPath = "bookstore/book"; // Get all books by default
if (param.BookId != 0) // According to the book ID Query
{
xPath = String.Format("/bookstore/book[@id='{0}']", param.BookId);
}
else if (!String.IsNullOrEmpty(param.Category)) // Query by book category
{
xPath = String.Format("/bookstore/book[@category='{0}']", param.Category);
}
else if (!String.IsNullOrEmpty(param.Title)) // Query by book name
{
xPath = String.Format("/bookstore/book[title='{0}']", param.Title);
}
XmlNodeList booksXmlNodeList = _booksXmlDoc.SelectNodes(xPath);
foreach (XmlNode bookNode in booksXmlNodeList)
{
BookInfo bookInfo = new BookInfo();
bookInfo.BookId = Convert.ToInt32(bookNode.Attributes["id"].Value); // Get the property value
bookInfo.Category = bookNode.Attributes["category"].Value;
bookInfo.Language = bookNode.SelectSingleNode("title").Attributes["lang"].Value; // Gets the attribute value of the child node
bookInfo.Title = bookNode.SelectSingleNode("title").InnerText; // Get Element Value
bookInfo.Author = bookNode.SelectSingleNode("author").InnerText;
bookInfo.Year = bookNode.SelectSingleNode("year").InnerText;
bookInfo.Price = Convert.ToDecimal(bookNode.SelectSingleNode("price").InnerText);
bookInfoList.Add(bookInfo);
}
return bookInfoList;
}
/// <summary>
/// Add book information (increase)
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public bool AddBookInfo(BookInfo param)
{
bool result = false;
XmlNode root = _booksXmlDoc.SelectSingleNode("bookstore"); // Find <bookstore>
// Create Node
XmlElement bookXmlElement = _booksXmlDoc.CreateElement("book");
XmlElement titleXmlElement = _booksXmlDoc.CreateElement("title");
XmlElement authorXmlElement = _booksXmlDoc.CreateElement("author");
XmlElement yearXmlElement = _booksXmlDoc.CreateElement("year");
XmlElement priceXmlElement = _booksXmlDoc.CreateElement("price");
// Assign a value to a node
bookXmlElement.SetAttribute("id", param.BookId.ToString());
bookXmlElement.SetAttribute("category", param.Category);
titleXmlElement.InnerText = param.Title; // Add element values to nodes
titleXmlElement.SetAttribute("lang", param.Language);// Add attribute values to nodes
authorXmlElement.InnerText = param.Author;
yearXmlElement.InnerText = param.Year;
priceXmlElement.InnerText = param.Price.ToString();
//AppendChild Adds the specified node to the end of the list of child nodes for that node
bookXmlElement.AppendChild(titleXmlElement);
bookXmlElement.AppendChild(authorXmlElement);
bookXmlElement.AppendChild(yearXmlElement);
bookXmlElement.AppendChild(priceXmlElement);
root.AppendChild(bookXmlElement);
_booksXmlDoc.Save(_basePath);
result = true;
return result;
}
/// <summary>
/// Modify book information
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public bool EditBookInfo(BookInfo param)
{
bool result = false;
if(param.BookId>0)
{
string xPath = String.Format("/bookstore/book[@id='{0}']", param.BookId);
XmlNode editXmlNode = _booksXmlDoc.SelectSingleNode(xPath);
XmlElement editXmlElement = (XmlElement)editXmlNode;
if (editXmlElement != null)
{
editXmlElement.Attributes["category"].Value = param.Category;
editXmlElement.SelectSingleNode("title").Attributes["lang"].Value = param.Language;
editXmlElement.SelectSingleNode("title").InnerText = param.Title;
editXmlElement.SelectSingleNode("author").InnerText = param.Author;
editXmlElement.SelectSingleNode("year").InnerText = param.Year;
editXmlElement.SelectSingleNode("price").InnerText = param.Price.ToString();
_booksXmlDoc.Save(_basePath);
result = true;
}
}
return result;
}
/// <summary>
/// Delete book information (delete)
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public bool DeleteBookInfo(BookInfo param)
{
bool result = false;
if (param.BookId > 0)
{
string xPath = String.Format("/bookstore/book[@id='{0}']", param.BookId);
XmlNode delXmlNode = _booksXmlDoc.SelectSingleNode(xPath);
if (delXmlNode != null)
{
_booksXmlDoc.SelectSingleNode("bookstore").RemoveChild(delXmlNode); // Removes the specified child node
_booksXmlDoc.Save(_basePath);
result = true;
}
}
return result;
}
}
PS: Here are some practical online tools related to xml for everyone to use:
Online XML Formatting/Compression Tool:
http://tools.ofstack.com/code/xmlformat
Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson
XML Online Compression/Formatting Tools:
http://tools.ofstack.com/code/xml_format_compress
XML code online formatting beautification tool:
http://tools.ofstack.com/code/xmlcodeformat
For more readers interested in C # related content, please check the topics on this site: "Summary of XML File Operation Skills in C #", "C # Common Control Usage Tutorial", "C # Programming Thread Use Skills Summary", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"
I hope this article is helpful to everyone's C # programming.