xml使用系统整理
1、 认识xml
可扩展标记语言,一种用于标记电子文档使其具有结果性的标记语言,它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。
2、 和超文本标记语言区别
2.1 html不一定需要成对出现,xml则一定需要成对出现。
2.2 html 不区分大小写,但是xml区分。
3、对xml文档增删改查
//声明一个XmlDocument空对象
protected XmlDocument XmlDoc = new XmlDocument();
/// <summary>
/// 构造函数,导入xml文件
/// </summary>
/// <param name="path"></param>
public XmlHelper(string path)
{
try
{
XmlDoc.Load(path);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="path"></param>
public void SaveXml(string path)
{
try
{
XmlDoc.Save(path);
}
catch (System.Exception ex)
{
throw ex;
}
}
/// <summary>
/// 获取节点的子节点的内容
/// </summary>
/// <param name="path"></param>
/// <param name="rootNode"></param>
/// <param name="attributeName"></param>
/// <returns></returns>
public string GetNodeChildAttribute(string path, string rootNode, string attributeName)
{
XmlNode xn = XmlDoc.SelectSingleNode(rootNode);
StringBuilder sb = new StringBuilder();
XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xnf in xnl)
{
XmlElement xe = (XmlElement)xnf;
XmlNodeList xnf1 = xe.ChildNodes;
foreach (XmlNode xn2 in xnf1)
{
if (xn2.Name == attributeName)
{
sb.Append(xn2.InnerText);//显示子节点点文本
}
}
}
return sb.ToString();
}
/// <summary>
/// 获取节点的属性值
/// </summary>
/// <param name="path">xml路径</param>
/// <param name="rootNode">根节点名称</param>
/// <param name="attributeName">属性名称</param>
/// <returns></returns>
public string GetNodeAttribute(string path, string rootNode, string attributeName)
{
try
{
XmlNode xn = XmlDoc.SelectSingleNode(rootNode);
XmlNodeList xnl = xn.ChildNodes;
StringBuilder sb = new StringBuilder();
foreach (XmlNode xnf in xnl)
{
XmlElement xe = (XmlElement)xnf;
sb.Append(xe.GetAttribute(attributeName));
}
return sb.ToString();
}
catch (Exception)
{ throw;
}
}
/// <summary>
/// 删除节点/节点属性
/// </summary>
/// <param name="path">xml文件地址</param>
/// <param name="rootNode">根节点名称</param>
/// <param name="delNode">要删除的节点</param>
/// <param name="attributeName">节点属性</param>
/// <param name="attributeValue">属性值</param>
public void DeleteNode(string path, string rootNode, string attributeName, string attributeValue)
{
try
{
XmlNodeList xnl = XmlDoc.SelectSingleNode(rootNode).ChildNodes;
foreach (XmlNode xn in xnl)
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute(attributeName) == attributeValue)
{
//xe.RemoveAttribute(attributeName);//删除属性
xe.RemoveAll();//删除该节点的全部内容
}
}
SaveXml(path);
}
catch (Exception)
{ throw;
}
}
/// <summary>
/// 修改节点的子节点内容
/// </summary>
/// <param name="path">xml文件路径</param>
/// <param name="rootNode">根节点名称</param>
/// <param name="attributeName">节点的子节点名称</param>
/// <param name="attributeOldValue">节点的子节点原始内容</param>
/// <param name="attributeNewValue">节点的子节点新内容</param>
public void UpdateChildNodeAttribute(string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue)
{
try
{
XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//获取根节点的所有子节点
foreach (XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue))
{
return;
}
else
{
XmlNodeList nls = xe.ChildNodes;
if (nls != null && nls.Count > )
{
foreach (XmlNode xn1 in nls)//遍历
{
XmlElement xe2 = (XmlElement)xn1;//转换类型
if (xe2.InnerText == attributeOldValue)//如果找到
{
xe2.InnerText = attributeNewValue;//则修改
break;//找到退出来就可以了
}
}
}
}
}
SaveXml(path);
}
catch (Exception)
{ throw;
}
}
/// <summary>
/// 修改节点属性值操作
/// </summary>
/// <param name="path">xml文件路径</param>
/// <param name="rootNode">根节点名称,如:bookstore</param>
/// <param name="attributeName">节点属性名</param>
/// <param name="attributeOldValue">节点属性原来值</param>
/// <param name="attributeNewValue">节点属性修改后的值</param>
public void UpdateNodeAttribute(string path, string rootNode, string attributeName, string attributeOldValue, string attributeNewValue)
{
try
{
XmlNodeList nodeList = XmlDoc.SelectSingleNode(rootNode).ChildNodes;//获取根节点的所有子节点
foreach (XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe = (XmlElement)xn;//将子节点类型专程xmlelement类型
if (string.IsNullOrEmpty(attributeName) || string.IsNullOrEmpty(attributeOldValue))
{
return;
}
else
{
if (xe.GetAttribute(attributeName) == attributeOldValue)
{
xe.SetAttribute(attributeName, attributeNewValue);
}
}
}
SaveXml(path);
}
catch (Exception)
{ throw;
}
}
/// <summary>
/// 插入节点操作
/// </summary>
/// <param name="path">xml文件路径</param>
/// <param name="rootNode">根节点名称,如:bookstore</param>
/// <param name="node">节点名称,如:book</param>
/// <param name="nodeAttributes">节点的属性-属性值集合</param>
/// <param name="childAttributes">节点子节点名称-内容</param>
public void InsertNode(string path, string rootNode, string node, Dictionary<string, string> nodeAttributes, Dictionary<string, string> childAttributes)
{
try
{
XmlNode root = XmlDoc.SelectSingleNode(rootNode);//找到根节点bookstore
XmlElement xe1 = XmlDoc.CreateElement(node);//创建子节点book
if (nodeAttributes != null && nodeAttributes.Count > )
{
foreach (var n in nodeAttributes)
{
xe1.SetAttribute(n.Key, n.Value);
}
}
if (childAttributes != null && childAttributes.Count > )
{
XmlElement xesub1;
foreach (var n in childAttributes)
{
xesub1 = XmlDoc.CreateElement(n.Key);
xesub1.InnerText = n.Value;
xe1.AppendChild(xesub1);//添加到<book>节点中
}
}
root.AppendChild(xe1);
SaveXml(path);
}
catch (Exception)
{ throw;
}
}
调用:
string path = Server.MapPath("Books.xml");
XmlHelper xHelper = new XmlHelper(path);
/*插入*/
//Dictionary<string, string> dc1 = new Dictionary<string, string>();
//dc1.Add("genre", "李赞红");
//dc1.Add("ISBN", "2-3631-4");
//Dictionary<strin插入g, string> dc2 = new Dictionary<string, string>();
//dc2.Add("title", "CS从入门到精通");
//dc2.Add("author", "候捷");
//dc2.Add("price", "58.3");
//xHelper.InsertNode(path, "bookstore", "book", dc1, dc2);
/*修改*/
//xHelper.UpdateNodeAttribute(path, "bookstore", "genre", "李赞红", "李");
//xHelper.UpdateChildNodeAttribute(path, "bookstore", "title", "CS从入门到精通", "cs");
/*删除节点*/
//xHelper.DeleteNode(path, "bookstore", "genre", "李");
//Response.Write(xHelper.GetNodeAttribute(path, "bookstore", "genre"));
//Response.Write(xHelper.GetNodeChildAttribute(path, "bookstore", "price"));
4、通过xml数据绑定
xml转DataTable
public DataTable XmlToData(string path, string rootNode, params string[] columns)
{
DataTable dt = new DataTable();
XmlNodeList xn = XmlDoc.SelectSingleNode(rootNode).ChildNodes;
try
{
if (columns.Length > )
{
DataColumn dc;
for (int i = ; i < columns.Length; i++)
{
dc = new DataColumn(columns[i]);
dt.Columns.Add(dc);
}
foreach (XmlNode xnf in xn)
{
XmlElement xe = (XmlElement)xnf;
XmlNodeList xnf1 = xe.ChildNodes;
int i = ;
DataRow dr = dt.NewRow();
foreach (XmlNode xn2 in xnf1)
{
dr[i] = xn2.InnerText;
i++;
}
dt.Rows.Add(dr);
}
}
}
catch (Exception)
{ throw;
}
return dt; }
调用:
//string[] arr = { "title", "author", "price" };
//GridView1.DataSource = xHelper.XmlToData(path, "bookstore", arr);
//GridView1.DataBind();
DataTable转xml
/*datatable转xml*/
public string DataTableToXml(DataTable dt)
{
if (dt != null)
{
MemoryStream ms = null;
XmlTextWriter XmlWt = null;
try
{
ms = new MemoryStream();
//根据ms实例化XmlWt
XmlWt = new XmlTextWriter(ms, Encoding.Unicode);
//获取ds中的数据
dt.WriteXml(XmlWt);
int count = (int)ms.Length;
byte[] temp = new byte[count];
ms.Seek(, SeekOrigin.Begin);
ms.Read(temp, , count);
//返回Unicode编码的文本
UnicodeEncoding ucode = new UnicodeEncoding();
string returnValue = ucode.GetString(temp).Trim();
return returnValue;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
//释放资源
if (XmlWt != null)
{
XmlWt.Close();
ms.Close();
ms.Dispose();
}
}
}
else
{
return "";
}
}
调用:
//bool s = xHelper.CDataToXmlFile(xHelper.XmlToData(path, "bookstore", arr), "Bookss.xml","book");
5、xml序列化反序列化
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class CXmlSerializer<T> where T : new()
{
private static XmlSerializer _Serializer = new XmlSerializer(typeof(T)); public static string Serialize(T t)
{
string s = "";
using (MemoryStream ms = new MemoryStream())
{
_Serializer.Serialize(ms, t);
s = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray());
}
return s;
} public static T Deserialize(string s)
{
T t;
using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s)))
{
t = (T)_Serializer.Deserialize(ms);
}
return t;
}
}
调用:
List<Person> list = new List<Person> { new Person { Name = "Xuj", Age = }, new Person { Name = "duj", Age = }, new Person { Name = "fuj", Age = } };
string s = CXmlSerializer<List<Person>>.Serialize(list);
xml使用系统整理的更多相关文章
- web.xml常用标签整理(不定期更新)
<?xml version="1.0" encoding="UTF-8"?><!-- 标明使用的XML版本和文档编码,此项必须位于第一行,之前 ...
- 如何开发mis系统--整理
1.含义: 所谓MIS(管理信息系统--Management Information System)系统,主要指的是进行日常事务操作的系统.这种系统主要用于管理需要的记录,并对记录数据进行相关处理,将 ...
- struts2知识系统整理
1.MVC 和 JSP Model 2 ** a.:M-Model 模型 包含两部分:业务数据和业务处理逻辑 b.V-View 视图:视图(View)的职责是负责显示界面和用户交互(收集用户信息 ...
- Java IO流系统整理
Java IO流的分类 Java中的流,可以从不同的角度进行分类. 按流向分类: 输入流: 程序可以从中读取数据的流.输出流: 程序能向其中写入数据的流. 按数据传输单位分类: 字节流:以字节(8位二 ...
- XML Schema——笔记整理
什么是 XML Schema? 定义可出现在文档中的元素 定义可出现在文档中的属性 定义哪个元素是子元素 定义子元素的次序 定义子元素的数目 定义元素是否为空,或者是否可包含文本 定义元素和属性的数据 ...
- iOS多线程系统整理 swift
多线程 是一个应用程序内多个代码的执行路径,执行线程,同时在同一时间里执行不同的任务. 三种: 1.NSTread 2.Cocoa NSOperation (NSOperation,NSOpera ...
- Spring 配置定时器(注解+xml)方式—整理
一.注解方式 1. 在Spring的配置文件ApplicationContext.xml,首先添加命名空间 xmlns:task="http://www.springframework.or ...
- C# XML类学习整理(待补)
一.读取xml文件内容: #region "获取xml文件内容" //将xml文件加载进来 XDocument xdoc = XDocument.Load("F:\\6. ...
- maven中pom.xml中配置整理: groupId、artifactId、parent、dependency、dependencyManagement区别
<groupId>com.mycompany.commonmaven</groupId> <artifactId>commonmaven</artifactI ...
随机推荐
- final static T
/** * An empty table instance to share when the table is not inflated. */ static final Entry<?,?& ...
- when not exists 用法
USE [ChangHong_612]GO/****** Object: StoredProcedure [dbo].[st_MES_UpdateInspectResult] Script Date: ...
- 在Hibernate中使用HibernateTemplate来进行包含sql语句的查询
/** * 使用sql语句进行查询操作 * @param sql * @return */ public List queryWithSql(final Stri ...
- 我的第一个javascript网页作业
1: <html> 2: <title> 3: 4: </title> 5: <body> 6: <style type="text ...
- java.io.File类
java.io.File类 1.凡是与输入.输出相关的类.接口等都定义在java.io包下 2.File是一个类.能够有构造器创建其对象.此对象相应着一个文件(.txt .avi .doc .ppt ...
- 基础数据结构 之 队列(python实现)
队也是编程开发中常见的一种数据结构.栈和队可用来模拟函数的递归过程.队的特点为先入先出,主要操作包括入队和出队.入队时需判断队是否已满,出队时需判断队是否为空.下面给出一个队的python实现的例子: ...
- 解决MySQL不允许从远程访问的方法
mysql -u root -p mysql>use mysql; mysql>select 'host' from user where user='root'; mysql>up ...
- WIN8重见开始菜单
从win7进入win8感觉不适应,做为一个程序开发人员,更觉得不爽,因此想着如何恢复开始菜单,查了很多文章终于找到方法 首先,在桌面版Windows 8启动资源管理器,单击工具栏上的“查看”选项卡后, ...
- Android 实现书籍翻页效果----完结篇
By 何明桂(http://blog.csdn.net/hmg25) 转载请注明出处 之前由于种种琐事,暂停了这个翻页效果的实现,终于在这周末完成了大部分功能,但是这里只是给出了一个基本的雏形,没有添 ...
- PHP写入文件用file_put_contents代替fwrite优点多多(转)
使用php有一段时间了,之前一直用fwrite写入文件,不过当我知道file_put_contents这个函数之后,fwrite就比较少用了,file_put_contents比fwrite代码更简洁 ...