C#实现XML文档的增删改查功能示例
本文实例讲述了C#实现XML文档的增删改查功能。分享给大家供大家参考,具体如下:
1、创建实例XML文件(Books.xml)
<?xmlversion="1.0"encoding="iso-8859-1"?> <bookstore> <bookid="1"category="COOKING"> <titlelang="en">EverydayItalian</title> <author>GiadaDeLaurentiis</author> <year>2005</year> <price>30.00</price> </book> <bookid="2"category="CHILDREN"> <titlelang="en">HarryPotter</title> <author>JK.Rowling</author> <year>2005</year> <price>29.99</price> </book> <bookid="3"category="WEB"> <titlelang="en">XQueryKickStart</title> <author>JamesMcGovern</author> <author>PerBothner</author> <author>KurtCagle</author> <author>JamesLinn</author> <author>VaidyanathanNagarajan</author> <year>2003</year> <price>49.99</price> </book> <bookid="4"category="WEB"> <titlelang="en">LearningXML</title> <author>ErikT.Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
2、创建图书信息实体类(BookInfo.cs)
publicclassBookInfo
{
///<summary>
///图书ID
///</summary>
publicintBookId{set;get;}
///<summary>
///图书名称
///</summary>
publicstringTitle{set;get;}
///<summary>
///图书分类
///</summary>
publicstringCategory{set;get;}
///<summary>
///图书语言
///</summary>
publicstringLanguage{set;get;}
///<summary>
///图书作者
///</summary>
publicstringAuthor{set;get;}
///<summary>
///出版时间
///</summary>
publicstringYear{set;get;}
///<summary>
///销售价格
///</summary>
publicdecimalPrice{set;get;}
}
3、创建图书信息业务逻辑类(BookInfoBLL.cs)
usingSystem.Xml;//引用相关文件
publicclassBookInfoBLL
{
privatestring_basePath=AppDomain.CurrentDomain.SetupInformation.ApplicationBase+@"/xml/Books.xml";//XML文件路径
privateXmlDocument_booksXmlDoc=null;//创建XML文档对象
publicBookInfoBLL()
{
try
{
_booksXmlDoc=newXmlDocument();//初始化XML文档对象
_booksXmlDoc.Load(_basePath);//加载指定的XML文档
}
catch(Exceptionex)
{
thrownewException("加载XML文档出错:"+ex.Message);
}
}
///<summary>
///获取图书列表(查)
///</summary>
///<paramname="param">参数条件</param>
///<returns>图书列表</returns>
publicList<BookInfo>GetBookInfoList(BookInfoparam)
{
List<BookInfo>bookInfoList=newList<BookInfo>();
stringxPath="bookstore/book";//默认获取所有图书
if(param.BookId!=0)//根据图书ID查询
{
xPath=String.Format("/bookstore/book[@id='{0}']",param.BookId);
}
elseif(!String.IsNullOrEmpty(param.Category))//根据图书类别查询
{
xPath=String.Format("/bookstore/book[@category='{0}']",param.Category);
}
elseif(!String.IsNullOrEmpty(param.Title))//根据图书名称查询
{
xPath=String.Format("/bookstore/book[title='{0}']",param.Title);
}
XmlNodeListbooksXmlNodeList=_booksXmlDoc.SelectNodes(xPath);
foreach(XmlNodebookNodeinbooksXmlNodeList)
{
BookInfobookInfo=newBookInfo();
bookInfo.BookId=Convert.ToInt32(bookNode.Attributes["id"].Value);//获取属性值
bookInfo.Category=bookNode.Attributes["category"].Value;
bookInfo.Language=bookNode.SelectSingleNode("title").Attributes["lang"].Value;//获取子节点的属性值
bookInfo.Title=bookNode.SelectSingleNode("title").InnerText;//获取元素值
bookInfo.Author=bookNode.SelectSingleNode("author").InnerText;
bookInfo.Year=bookNode.SelectSingleNode("year").InnerText;
bookInfo.Price=Convert.ToDecimal(bookNode.SelectSingleNode("price").InnerText);
bookInfoList.Add(bookInfo);
}
returnbookInfoList;
}
///<summary>
///增加图书信息(增)
///</summary>
///<paramname="param"></param>
///<returns></returns>
publicboolAddBookInfo(BookInfoparam)
{
boolresult=false;
XmlNoderoot=_booksXmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
//创建节点
XmlElementbookXmlElement=_booksXmlDoc.CreateElement("book");
XmlElementtitleXmlElement=_booksXmlDoc.CreateElement("title");
XmlElementauthorXmlElement=_booksXmlDoc.CreateElement("author");
XmlElementyearXmlElement=_booksXmlDoc.CreateElement("year");
XmlElementpriceXmlElement=_booksXmlDoc.CreateElement("price");
//给节点赋值
bookXmlElement.SetAttribute("id",param.BookId.ToString());
bookXmlElement.SetAttribute("category",param.Category);
titleXmlElement.InnerText=param.Title;//给节点添加元素值
titleXmlElement.SetAttribute("lang",param.Language);//给节点添加属性值
authorXmlElement.InnerText=param.Author;
yearXmlElement.InnerText=param.Year;
priceXmlElement.InnerText=param.Price.ToString();
//AppendChild将指定的节点添加到该节点的子节点列表的末尾
bookXmlElement.AppendChild(titleXmlElement);
bookXmlElement.AppendChild(authorXmlElement);
bookXmlElement.AppendChild(yearXmlElement);
bookXmlElement.AppendChild(priceXmlElement);
root.AppendChild(bookXmlElement);
_booksXmlDoc.Save(_basePath);
result=true;
returnresult;
}
///<summary>
///修改图书信息(改)
///</summary>
///<paramname="param"></param>
///<returns></returns>
publicboolEditBookInfo(BookInfoparam)
{
boolresult=false;
if(param.BookId>0)
{
stringxPath=String.Format("/bookstore/book[@id='{0}']",param.BookId);
XmlNodeeditXmlNode=_booksXmlDoc.SelectSingleNode(xPath);
XmlElementeditXmlElement=(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;
}
}
returnresult;
}
///<summary>
///删除图书信息(删)
///</summary>
///<paramname="param"></param>
///<returns></returns>
publicboolDeleteBookInfo(BookInfoparam)
{
boolresult=false;
if(param.BookId>0)
{
stringxPath=String.Format("/bookstore/book[@id='{0}']",param.BookId);
XmlNodedelXmlNode=_booksXmlDoc.SelectSingleNode(xPath);
if(delXmlNode!=null)
{
_booksXmlDoc.SelectSingleNode("bookstore").RemoveChild(delXmlNode);//移除指定的子节点
_booksXmlDoc.Save(_basePath);
result=true;
}
}
returnresult;
}
}
PS:这里再为大家提供几款比较实用的xml相关在线工具供大家使用:
在线XML格式化/压缩工具:
http://tools.jb51.net/code/xmlformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《C#程序设计之线程使用技巧总结》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》
希望本文所述对大家C#程序设计有所帮助。
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短