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 ...
随机推荐
- Java 执行jar linux 实例
需求:通过执行jar的方式 ,把某个文件路径下的用户数据同步到redis 1.main 函数 public class Main { private static Logger logger = Lo ...
- SwipeListView 具体解释 实现微信,QQ等滑动删除效果
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/28508769 今天看别人项目,看到别人使用了SwipeListView,Goog ...
- BZOJ 1806 IOI2007 Miners 矿工配餐 动态规划
题目大意:将一个123序列拆分为两个子序列.定义每一个数的贡献值为以这个数结尾的长度最大为3的子串中不同数的数量,求贡献值和的最大值 令f[i][a1][a2][b1][b2]为前i个数分成两组,第一 ...
- 【2014】【辛星】【php】【秋季】【2】第一个php程序
<span style="font-family:KaiTi_GB2312;font-size:18px;">*******************设置server** ...
- Merge into的使用具体解释-你Merge了没有
Merge是一个很实用的功能,相似于Mysql里的insert into on duplicate key. Oracle在9i引入了merge命令, 通过这个merge你可以在一个SQL语句中对一 ...
- Web classPath
classpath,看名字,类路径,这样比如,对于java程序,就是告诉java程序哪里去找类.(java虚拟机都是通过类装载器的)想myeclipse中struts,spring,hibernate ...
- Eclipse / Android : “Errors running builder 'Android Pre Compiler' on project…”
Errors occurred during the build. Errors running builder 'Android Resource Manager' on project 'hell ...
- Oracle中wm_concat()的使用方法
以下两种方式使用wm_concat()的使用方法是等效的. 方法一:使用窗口函数,wm_concat支持窗口函数 select distinct classKey,className, classOr ...
- [原创] SQLite数据库使用清单(下)
上文两章对SQLite的功能.语法.和操作进行了介绍,本文讲解SQLite的一些高级语法和操作. 3.
- Datum Form Goole Android
1. <TurboChargeYourUI-How to make your AndroidUI fast and efficient> 2. <The World of List ...