C#操作xml的3种方式
XmlDocumentDataSetlinq to xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book display="书本记录">
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="B02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book id="B03">
<name>水浒</name>
<price>6</price>
<memo>四大名著之一。</memo>
</book>
<book id="B04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book>
</books>
以下代码只适用于测试学习,不适用于工程代码
1. XmlDocument【传统方式】
/// <summary>
/// XmlDocument增删改查
/// </summary>
public static void XmlDocumentOP()
{
XmlElement theBook = null, theElem = null, root = null;
XmlDocument xmldoc = new XmlDocument();
try
{
xmldoc.Load("Books.xml");
root = xmldoc.DocumentElement; //--- 新建一本书开始 ----
theBook = xmldoc.CreateElement("book");
theElem = xmldoc.CreateElement("name");
theElem.InnerText = "新书";
theBook.AppendChild(theElem); theElem = xmldoc.CreateElement("price");
theElem.InnerText = "";
theBook.AppendChild(theElem); theElem = xmldoc.CreateElement("memo");
theElem.InnerText = "新书更好看。";
theBook.AppendChild(theElem);
root.AppendChild(theBook);
Console.Out.WriteLine("--- 新建一本书开始 ----");
Console.Out.WriteLine(root.OuterXml);
//--- 新建一本书完成 ---- //--- 下面对《哈里波特》做一些修改。 ----
//--- 查询找《哈里波特》----
theBook = (XmlElement)root.SelectSingleNode("/books/book[name='哈里波特']");
Console.Out.WriteLine("--- 查找《哈里波特》 ----");
Console.Out.WriteLine(theBook.OuterXml);
//--- 此时修改这本书的价格 -----
theBook.GetElementsByTagName("price").Item().InnerText = "";//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,GetElementsByTagName("price")相当于SelectNodes(".//price")。
Console.Out.WriteLine("--- 此时修改这本书的价格 ----");
Console.Out.WriteLine(theBook.OuterXml);
//--- 另外还想加一个属性id,值为B01 ----
theBook.SetAttribute("id", "B01");
Console.Out.WriteLine("--- 另外还想加一个属性id,值为B01 ----");
Console.Out.WriteLine(theBook.OuterXml);
//--- 对《哈里波特》修改完成。 ---- //--- 再将所有价格低于10的书删除 ----
theBook = (XmlElement)root.SelectSingleNode("/books/book[@id='B02']");
Console.Out.WriteLine("--- 要用id属性删除《三国演义》这本书 ----");
Console.Out.WriteLine(theBook.OuterXml);
theBook.ParentNode.RemoveChild(theBook);
Console.Out.WriteLine("--- 删除后的XML ----");
Console.Out.WriteLine(xmldoc.OuterXml); //--- 再将所有价格低于10的书删除 ----
XmlNodeList someBooks = root.SelectNodes("/books/book[price<10]");
Console.Out.WriteLine("--- 再将所有价格低于10的书删除 ---");
Console.Out.WriteLine("--- 符合条件的书有 " + someBooks.Count + "本。 ---"); for (int i = ; i < someBooks.Count; i++)
{
someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
}
Console.Out.WriteLine("--- 删除后的XML ----");
Console.Out.WriteLine(xmldoc.OuterXml); xmldoc.Save("books.xml");//保存到books.xml Console.In.Read();
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
} }
以上代码来源于网络测试可行,作者忘记了
2. DataSet 操作xml【常用方式】
/// <summary>
/// DataSet操作xml
/// </summary>
public static void XmlDataSetOP()
{
DataSet ds = new DataSet();
ds.ReadXml("books.xml");
/*
<books>
<book display="书本记录">
<name>哈里波特</name>
<price>10</price>
<memo>这是一本很好看的书。</memo>
</book>
<book id="B02">
<name>三国演义</name>
<price>10</price>
<memo>四大名著之一。</memo>
</book>
<book1 id="B04">
<name>红楼</name>
<price>5</price>
<memo>四大名著之一。</memo>
</book1>
</books>
*/
//ds 是多表集合,根节点没有实际意义,这样会生成两个数据表:book 和 book1
//book 表包含了子节点及属性所有节点的字段
//即 name price memo display id
// 哈里波特 10 这是…书。 书本记录 B01
// 三国演义 10 四大…之一。 B02 //注意如果以上子节点含有属性,可能会建立关系表,如<name provice="english">哈里波特</name> 比较复杂
DataTable dt = ds.Tables["book"];
//查找数据
//1. 查询价格等于10的row记录
var row = dt.Select("price = 10");
//2. 查询价格等于10的记录 并且 name是 哈里波特的
var row1 = dt.Select("price = 10 and name = '哈里波特'"); //3.将DataTable 实现IEnumerable接口,AsEnumerable(),然后使用linq查询
var ss = from rowData in dt.AsEnumerable().Where(r => r["price"].ToString() == "")
where ==
select new { a = rowData["name"].ToString() }; //增加数据
dt.Rows.Add(new object[] { "aaa", , });//注意这里请按照字段顺序编写,字段顺序:book子节点、book属性
//ds.GetXml();可直接输出当前最新xml,保存即可 //移除了这个条件下的记录
foreach (var item in dt.Select("price=10"))
{
dt.Rows.Remove(item);
}
//改,
var cRow = dt.Select("name='水浒'");
if (cRow.Count() > )
{
cRow[].BeginEdit();
cRow[]["name"] = "水浒传";
cRow[]["price"] = "";
cRow[].EndEdit();
} }
3. linq to Xml【比较人性化方式,据说效率最佳】
class Book
{
public string ID { get; set; }
public string Display { get; set; }
public string Name { get; set; }
public string Price { get; set; }
public string Memo { get; set; } private static XDocument doc = new XDocument();
public static string filePath = "books.xml";
public Book()
{
doc = XDocument.Load(filePath);
} public Book(string filepath)
{
filePath = filepath;
doc = XDocument.Load(filePath);
} /// <summary>
/// 增
/// </summary>
/// <returns></returns>
public bool Add()
{
XElement db = new XElement("book",
new XAttribute("id", Guid.NewGuid().ToString()),
new XAttribute("display", Display),
new XElement("name", Name),
new XElement("price", Price),
new XElement("memo", Memo)
);
try
{
//用XElement的Add方法
//XElement doc = XElement.Load(filePath);
//doc.Add(db);
//用XDocument的Add方法
doc.Element("books").Add(db);
doc.Save(filePath);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 删
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool RemoveData(string id)
{
XElement xe = (from db in doc.Element("books").Elements("book")
where (db.Attribute("id") == null ? "" : db.Attribute("id").Value) == id
select db).Single() as XElement;
try
{
xe.Remove();
doc.Save(filePath);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 改
/// </summary>
/// <returns></returns>
public bool Update()
{
XElement xe = (from db in doc.Element("books").Elements("book")
where (db.Attribute("id") == null ? "" : db.Attribute("id").Value.ToString()) == ID
select db).Single();
try
{
xe.Attribute("display").Value = Display;
xe.Element("name").Value = Name;
xe.Element("price").Value = Price;
xe.Element("memo").Value = Memo;
doc.Save(filePath);
return true;
}
catch
{
return false;
}
} /// <summary>
/// 查
/// </summary>
/// <returns></returns>
public List<Book> GetAll()
{
List<Book> dbs = (from db in doc.Element("books").Elements("book")
select new Book
{
ID = db.Attribute("id") == null ? "" : db.Attribute("id").Value.ToString(),
Display = db.Attribute("display") == null ? "" : db.Attribute("display").Value.ToString(),
Name = db.Element("name") == null ? "" : db.Element("name").Value.ToString(),
Price = db.Element("price") == null ? "" : db.Element("name").Value.ToString(),
Memo = db.Element("memo") == null ? "" : db.Element("name").Value.ToString()
}).ToList();
return dbs;
}
/// <summary>
/// 查
/// </summary>
/// <returns></returns>
public List<Book> TakePage(out int totalSize, int index, int size)
{
List<Book> dbs = (from db in doc.Element("books").Elements("book")
select new Book
{
ID = db.Attribute("id") == null ? "" : db.Attribute("id").Value.ToString(),
Display = db.Attribute("display") == null ? "" : db.Attribute("display").Value.ToString(),
Name = db.Element("name") == null ? "" : db.Element("name").Value.ToString(),
Price = db.Element("price") == null ? "" : db.Element("name").Value.ToString(),
Memo = db.Element("memo") == null ? "" : db.Element("name").Value.ToString()
}).Skip((index - ) * size).Take(size).ToList();
totalSize = GetAll().Count;
return dbs;
}
/// <summary>
/// 查
/// </summary>
/// <returns></returns>
public List<Book> GetSingleBook(string id)
{
List<Book> dbs = (from db in doc.Element("books").Elements("book")
where (db.Attribute("id") == null ? "" : db.Attribute("id").Value.ToString()) == id
select new Book
{
ID = db.Attribute("id") == null ? "" : db.Attribute("id").Value.ToString(),
Display = db.Attribute("display") == null ? "" : db.Attribute("display").Value.ToString(),
Name = db.Element("name") == null ? "" : db.Element("name").Value.ToString(),
Price = db.Element("price") == null ? "" : db.Element("name").Value.ToString(),
Memo = db.Element("memo") == null ? "" : db.Element("name").Value.ToString()
}).ToList();
return dbs;
}
}
C#操作xml的3种方式的更多相关文章
- android操作XML的几种方式(转)
XML作为一种业界公认的数据交换格式,在各个平台与语言之上,都有广泛使用和实现.其标准型,可靠性,安全性......毋庸置疑.在android平台上,我们要想实现数据存储和数据交换,经常会使用到xml ...
- 简介C#读取XML的两种方式
简介C#读取XML的两种方式 作者: 字体:[增加 减小] 类型:转载 时间:2013-03-03 在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型,使用DOM的 ...
- JAVA解析XML的四种方式
java解析xml文件四种方式 1.介绍 1)DOM(JAXP Crimson解析器) DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准.DOM是以层次结构组织的节点或信息片断的集合.这 ...
- java解析xml的几种方式
java解析xml的几种方式 DOM DOM的全称是Document ObjectModel,也即文档对象模型.在应用程序中,基于DOM的XML分析器将一个XML文档转换成一个对象模型的集合(通常称D ...
- Hadoop之HDFS文件操作常有两种方式(转载)
摘要:Hadoop之HDFS文件操作常有两种方式,命令行方式和JavaAPI方式.本文介绍如何利用这两种方式对HDFS文件进行操作. 关键词:HDFS文件 命令行 Java API HD ...
- flask 操作mysql的两种方式-sqlalchemy操作
flask 操作mysql的两种方式-sqlalchemy操作 二.ORM sqlalchemy操作 #coding=utf-8 # model.py from app import db class ...
- flask 操作mysql的两种方式-sql操作
flask 操作mysql的两种方式-sql操作 一.用常规的sql语句操作 # coding=utf-8 # model.py import MySQLdb def get_conn(): conn ...
- c#操作json的两种方式
总结一下C#操作json的两种方式,都是将对象和json格式相转. 1.JavaScriptSerializer,继承自System.Web.Script.Serialization private ...
- Python 操作 MySQL 的5种方式(转)
Python 操作 MySQL 的5种方式 不管你是做数据分析,还是网络爬虫,Web 开发.亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Pytho ...
随机推荐
- sdut-2725-The Urge to Merge-状压DP
把数组竖起来,从上往下走. 如果当前位置是竖着乘的,那么第一个点标记为1.否则标记为0. 样例最终的状态为: 0 0 1 0 1 0 1 0 0 0 0 0 #include<iostream& ...
- 去除android ImageView “[Accessibility] Missing contentDescription attribute on image” warning
1.在有警告的xml上选择Graphical Layout: 2.查看右上角的被涂鸦的地方,然后点击: 3.出现: 4.点击”Ignore Type“或者是“Disable Issue Type”(不 ...
- AlphaDict 软件公布
今天 Release 了 1.1. 主要是移植到了 window 平台, 无须安装,直接执行. 对 UI 又一次进行了设计,应该比之前好看多了. 加入了 生词本 功能,方便 学习外语. ------- ...
- [转][JAVA]定时任务之-Quartz使用篇
[BAT][JAVA]定时任务之-Quartz使用篇 定时任务之-Quartz使用篇 Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与 ...
- Linux多线程——使用互斥量同步线程
前文再续,书接上一回,在上一篇文章: Linux多线程——使用信号量同步线程中,我们留下了一个如何使用互斥量来进行线程同步的问题,本文将会给出互斥量的详细解说,并用一个互斥量解决上一篇文章中,要使用两 ...
- python第三方库推荐 - 通过ntplib在windows上同步时间
很多时候我们有通过程序脚本同步校正北京时间的需求. 在linux上同步时间比较方便,安装个ntpdate软件就行了. 但是在windows的要同步时间比较麻烦. 这时想到的就是从网络获取一个准确的时间 ...
- valgrind 打印程序调用树+进行多线程性能分析
使用valgrind的callgrind工具进行多线程性能分析 yum install valgrind / wget http://valgrind.org/downloads/valgrind-3 ...
- Qt 学习之路 :视图代理
与 Qt model/view 架构类似,在自定义用户界面中,代理扮演着重要的角色.模型中的每一个数据项都要通过一个代理向用户展示,事实上,用户看到的可视部分就是代理. 每一个代理都可以访问一系列属性 ...
- java面试32问
第一,谈谈final, finally, finalize的区别. 第二,Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements ...
- HTTP协议 状态码详解
http://www.cnblogs.com/TankXiao/archive/2013/01/08/2818542.html