C#操作XML方法集合
一 前言
先来了解下操作XML所涉及到的几个类及之间的关系 如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家
* 1 XMLElement 主要是针对节点的一些属性进行操作
* 2 XMLDocument 主要是针对节点的CUID操作
* 3 XMLNode 为抽象类,做为以上两类的基类,提供一些操作节点的方法
清楚了以上的关系在操作XML时会更清晰一点
二 具体操作(C#)
以下会对Xml的结点与属性做增 删 改 查的操作也满足了实际工作中的大部分情况
先构造一棵XML树如下,其中也涉及到了写入xml文档的操作
public void CreatXmlTree(string xmlPath)
{
XElement xElement = new XElement(
new XElement("BookStore",
new XElement("Book",
new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
new XElement("Adress", "上海"),
new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
),
new XElement("Book",
new XElement("Name", "WCF入门", new XAttribute("BookName", "WCF")),
new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
new XElement("Adress", "北京"),
new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
)
)
); //需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.Indent = true;
XmlWriter xw = XmlWriter.Create(xmlPath,settings);
xElement.Save(xw);
//写入文件
xw.Flush();
xw.Close();
}
然后得到如下的XML树
<?xml version="1.0" encoding="utf-8"?>
<BookStore>
<Book>
<Name BookName="C#">C#入门</Name>
<Author Name="Martin">Martin</Author>
<Date>2013-10-11</Date>
<Adress>上海</Adress>
<Date>2013-10-11</Date>
</Book>
<Book>
<Name BookName="WCF">WCF入门</Name>
<Author Name="Mary">Mary</Author>
<Adress>北京</Adress>
<Date>2013-10-11</Date>
</Book>
</BookStore>
以下操作都是对生成的XML树进行操作
2.1 新增节点与属性
新增节点NewBook并增加属性Name="WPF"
public void Create(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath); var root = xmlDoc.DocumentElement;//取到根结点
XmlNode newNode = xmlDoc.CreateNode("element", "NewBook", "");
newNode.InnerText = "WPF"; //添加为根元素的第一层子结点
root.AppendChild(newNode);
xmlDoc.Save(xmlPath);
}
开篇有写操作xml节点属性主要用XmlElement对象所以取到结点后要转类型
//属性
public void CreateAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
var root = xmlDoc.DocumentElement;//取到根结点
XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
node.SetAttribute("Name", "WPF");
xmlDoc.Save(xmlPath); }
效果如下
2.2 删除节点与属性
public void Delete(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
var root = xmlDoc.DocumentElement;//取到根结点 var element = xmlDoc.SelectSingleNode("BookStore/NewBook");
root.RemoveChild(element);
xmlDoc.Save(xmlPath);
}
删除属性
public void DeleteAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
//移除指定属性
node.RemoveAttribute("Name");
//移除当前节点所有属性,不包括默认属性
//node.RemoveAllAttributes();
xmlDoc.Save(xmlPath);
}
2.3 修改节点与属性
xml的节点默认是不允许修改的,本文也就不做处理了
修改属性代码如下
public void ModifyAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
element.SetAttribute("Name", "Zhang");
xmlDoc.Save(xmlPath);
}
效果如下
2.4 获取节点与属性
public void Select(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
//取根结点
var root = xmlDoc.DocumentElement;//取到根结点
//取指定的单个结点
XmlNode oldChild = xmlDoc.SelectSingleNode("BookStore/NewBook"); //取指定的结点的集合
XmlNodeList nodes = xmlDoc.SelectNodes("BookStore/NewBook"); //取到所有的xml结点
XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
}
属性
public void SelectAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("BookStore/NewBook");
string name = element.GetAttribute("Name");
Console.WriteLine(name);
}
三 具体操作 (linq to XML)
Linq to Xml 也没什么变化只操作对象改变了主要涉及的几个对象如下 注:我并没有用linq的语法去操作元素。
XDocument:用于创建一个XML实例文档
XElement:用于一些节点与节点属性的基本操作
以下是对Xml的 一些简单的操作
3.1 新增节点与属性
public void Create(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
XElement xElement = xDoc.Element("BookStore");
xElement.Add(new XElement("Test", new XAttribute("Name", "Zery")));
xDoc.Save(xmlPath);
}
属性
public void CreateAttribute(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
IEnumerable<XElement> xElement = xDoc.Element("BookStore").Elements("Book");
foreach (var element in xElement)
{
element.SetAttributeValue("Name", "Zery");
}
xDoc.Save(xmlPath);
}
3.2 删除节点与属性
public void Delete(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
XElement element = (XElement)xDoc.Element("BookStore").Element("Book");
element.Remove();
xDoc.Save(xmlPath);
}
属性
public void DeleteAttribute(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
//不能跨级取节点
XElement element = xDoc.Element("BookStore").Element("Book").Element("Name");
element.Attribute("BookName").Remove();
xDoc.Save(xmlPath);
}
3.3 修改节点属性
节点.net没提供修改的方法本文也不做处理
修改属性与新增实质是同一个方法
public void ModifyAttribute(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
XElement element = xDoc.Element("BookStore").Element("Book");
element.SetAttributeValue("BookName","ZeryTest");
xDoc.Save(xmlPath);
}
四 总结
把文章写完时,又扫去了自己的一个盲区,虽然都是些简单的操作,但在实际的开中,又何尝不是由简单到复杂呢。我觉得身为程序员就应该遇到自己的盲区时,立马花时间去了解,不说要了解多深入,但至少基本的还是要知道,等到工作中真需时,只要稍微花点时间就可以了。
如果觉得文章对你有点帮助,不妨点下推荐,你的推荐让我对写文章能有更多的激情!
成长在于积累!
Demo 源码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Web;
using System.Xml.Linq; namespace XMLOperation
{
class Program
{
static void Main(string[] args)
{
/*=============Linq 读写XML==================*/
string wxmlPath = @"F:\XmlTest\test.xml";
XmlWriteReadLinqOperation writeReadLinq = new XmlWriteReadLinqOperation();
// writeReadLinq.WriteXml(wxmlPath);
writeReadLinq.CreatXmlTree(wxmlPath); //string xmlPath = @"F:\XML.xml";
string xmlPath = @"C:\Users\zery.zhang\Desktop\ProjectDemo\XML.xml";
/*
* 1 三者之间的关系用图画出
* 2 XMLElement 主要是针对节点的一些属性进行操作
* 3 XMLDocument 主要是针对节点的CUID操作
* 4 XMLNode 为抽象类,做为以上两类的基类,提供一些操作节点的方法
*/ //===========C# to Xml==========//
XmlOperation xmlOperation = new XmlOperation();
//xmlOperation.Create(xmlPath);
//xmlOperation.CreateAttribute(xmlPath); //xmlOperation.Delete(xmlPath);
//xmlOperation.DeleteAttribute(xmlPath); //xmlOperation.Modify(xmlPath);
//xmlOperation.ModifyAttribute(xmlPath); //xmlOperation.Select(xmlPath);
//xmlOperation.SelectAttribute(xmlPath);
/*=============Linq to Xml===========*/
XmlOperationToLinq xOperation = new XmlOperationToLinq();
// xOperation.Create(xmlPath);
/*
*1 给指定的XML节点的所有子节点增加一个节点,并增加属性
*2 删除指定节点的子节点的指定属性
*3
*/
string lxmlPath = @"F:\XmlTest\test.xml";
xOperation.Create(lxmlPath);
xOperation.CreateAttribute(lxmlPath);
//xperation.Delete(lxmlPath);
//xOperation.DeleteAttribute(lxmlPath);
// xOperation.ModifyAttribute(lxmlPath); /*=============C# 读写XML===============*/
XmlWriteReadOperation writeRead = new XmlWriteReadOperation(); Console.Read(); } } class XmlOperation
{ public void Create(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
var root = xmlDoc.DocumentElement;//取到根结点 XmlNode newNode = xmlDoc.CreateNode("element", "Name", "");
newNode.InnerText = "Zery"; //添加为根元素的第一层子结点
root.AppendChild(newNode);
xmlDoc.Save(xmlPath);
}
//属性
public void CreateAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
node.SetAttribute("Name", "C#");
xmlDoc.Save(xmlPath);
} public void Delete(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
var root = xmlDoc.DocumentElement;//取到根结点 var element = xmlDoc.SelectSingleNode("Collection/Name");
root.RemoveChild(element);
xmlDoc.Save(xmlPath);
} public void DeleteAttribute(string xmlPath)
{ XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement node = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
//移除指定属性
node.RemoveAttribute("Name");
//移除当前节点所有属性,不包括默认属性
node.RemoveAllAttributes(); xmlDoc.Save(xmlPath); } public void Modify(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
var root = xmlDoc.DocumentElement;//取到根结点
XmlNodeList nodeList = xmlDoc.SelectNodes("/Collection/Book");
//xml不能直接更改结点名称,只能复制然后替换,再删除原来的结点
foreach (XmlNode node in nodeList)
{
var xmlNode = (XmlElement)node;
xmlNode.SetAttribute("ISBN", "Zery");
}
xmlDoc.Save(xmlPath); } public void ModifyAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
element.SetAttribute("Name", "Zhang");
xmlDoc.Save(xmlPath); } public void Select(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
//取根结点
var root = xmlDoc.DocumentElement;//取到根结点
//取指定的单个结点
XmlNode singleNode = xmlDoc.SelectSingleNode("Collection/Book"); //取指定的结点的集合
XmlNodeList nodes = xmlDoc.SelectNodes("Collection/Book"); //取到所有的xml结点
XmlNodeList nodelist = xmlDoc.GetElementsByTagName("*");
} public void SelectAttribute(string xmlPath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlElement element = (XmlElement)xmlDoc.SelectSingleNode("Collection/Book");
string name = element.GetAttribute("Name"); }
} class XmlOperationToLinq
{
//其它操作
public void OtherOperaton()
{
//加文件头
} public void Create(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
XElement xElement = xDoc.Element("BookStore");
xElement.Add(new XElement("Test", new XAttribute("Name", "Zery")));
xDoc.Save(xmlPath);
} public void CreateAttribute(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
IEnumerable<XElement> xElement = xDoc.Element("BookStore").Elements("Book");
foreach (var element in xElement)
{
element.SetAttributeValue("Name", "Zery");
}
xDoc.Save(xmlPath);
} public void Delete(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
XElement element = (XElement)xDoc.Element("BookStore").Element("Book");
element.Remove();
xDoc.Save(xmlPath);
} public void DeleteAttribute(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
//不能跨级取节点
XElement element = xDoc.Element("BookStore").Element("Book").Element("Name");
element.Attribute("BookName").Remove();
xDoc.Save(xmlPath);
} public void ModifyAttribute(string xmlPath)
{
XDocument xDoc = XDocument.Load(xmlPath);
XElement element = xDoc.Element("BookStore").Element("Book");
element.SetAttributeValue("BookName","ZeryTest");
xDoc.Save(xmlPath);
} } internal class XmlWriteReadOperation
{ } class XmlWriteReadLinqOperation
{ public void CreatXmlTree(string xmlPath)
{
XElement xElement = new XElement(
new XElement("BookStore",
new XElement("Book",
new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
new XElement("Author", "Martin", new XAttribute("Name", "Martin")),
new XElement("Adress", "上海"),
new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
),
new XElement("Book",
new XElement("Name", "WCF入门", new XAttribute("BookName", "WCF")),
new XElement("Author", "Mary", new XAttribute("Name", "Mary")),
new XElement("Adress", "北京"),
new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
)
)
); //需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.Indent = true;
XmlWriter xw = XmlWriter.Create(xmlPath,settings);
xElement.Save(xw);
//写入文件
xw.Flush();
xw.Close();
} public void WriteXml(string xmlPath)
{
XElement xElement = new XElement(
new XElement("Store",
new XElement("Book", "技术类",
new XElement("Name", "C#入门", new XAttribute("BookName", "C#")),
new XElement("Author", "Martin", new XAttribute("Name", "Zery")),
new XComment("以下为注释"),//xml注释
new XElement("Date", DateTime.Now.ToString(), new XAttribute("PublicDate", DateTime.Now.ToString()))
))
); XmlWriter xw = XmlWriter.Create(xmlPath);
//保存到XmlWriter
xElement.Save(xw);
//写入文件
xw.Flush();
xw.Close(); } }
}
C#操作XML方法集合的更多相关文章
- js操作textarea方法集合
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...
- C#操作XML方法详解
using System.Xml; //初始化一个xml实例 XmlDocument xml=new XmlDocument(); //导入指定xml文件 xml.Load(path); xml. ...
- C#操作XML方法:新增、修改和删除节点与属性
一 前言 先来了解下操作XML所涉及到的几个类及之间的关系 如果大家发现少写了一些常用的方法,麻烦在评论中指出,我一定会补上的!谢谢大家 * 1 XMLElement 主要是针对节点的一些属性进行操 ...
- PHP操作XML方法之SimpleXML
SimpleXML简介 SimpleXML 扩展提供了一个非常简单和易于使用的工具集,能将XML转换成一个带有一般属性选择器和数组迭代器的对象. 举例XML XML结构部分引用自<<深入理 ...
- C#.Net操作XML方法二
上面那篇博客,在上面那面博客中是通过System.Xml命名空间中的类来实现对XML文件的创建.删除和改动等操作.接下来再介绍一种方法,在整个的操作过程中,仅仅只是换了个类而已,没什么大惊小怪的. D ...
- 24、java操作xml方法
XML解析方式 1. SAX解析方式 SAX(simple API for XML)是一种XML解析的替代方法.相比于DOM,SAX是一种速度更快,更有效的方法.它逐行扫描文档,一边扫描一边解析.而且 ...
- C# 操作IIS方法集合
如果在win8,win7情况下报错:未知错误(0x80005000) 见http://blog.csdn.net/ts1030746080/article/details/8741399 using ...
- 【分享】 封装js操作textarea 方法集合(兼容很好)。
请使用下面的btn操作. 虽然你现在看来没什么用,当要用的时候又到处找资料,还不如现在收集一下. 在DOM里面操作textarea里面的字符,是比较麻烦的. 于是我有这个封装分享给大家 ...
- PHP操作XML方法之 XML Expat Parser
XML Expat Parser 简介 此PHP扩展实现了使用PHP支持JamesClark编写的expat.此工具包可解析(但不能验证)XML文档.它支持PHP所提供的3种字符编码:US-ASCII ...
随机推荐
- 让vc2010的项目在vc2012也能直接使用,而不必修改PlatformToolSet
在Visual Studio 2010新建的项目到2012里打开会要求修改PlatformToolset的值,从v100改为v110.如果这个项目需要进版本管理(VCS,如git, svn),这将造成 ...
- 【故障处理】告警日志报“ORA-01565 Unable To open Spfile”
[故障处理]告警日志报"ORA-01565 Unable To open Spfile" 1.1 BLOG文档结构图 1.2 故障分析及解决过程 1.2.1 故障环境介绍 项 ...
- Navicat常用快捷键
[ctrl+q] 打开查询窗口 [ctrl+/] 注释sql语句 [ctrl+shift +/] 解除注释 [ctrl+r] ...
- Java设计模式学习笔记(观察者模式)
观察者模式说起来很简单,就是一个订报纸的模式.但是实际上这部分我觉得还是很有意思的,<Head First设计模式>里还有一些还没看完,也是因为理解的不够深吧. 观察者模式会包含两个组件: ...
- Windows Azure CN 超业余性能测试
先来说说为什么会有这篇文章吧.从朋友那里搞来个Windows Azure CN的测试帐号,在公司的时候领导的朋友有一个阿里云的服务器,平时部署小东西都往上面丢,不过那是人家的东西,还有其他的应用跑在上 ...
- To create my first app in iOS with Xcode(在Xcode创建我的第一个iOS app )
To create my first app in iOS create the project. In the welcome window, click “Create a new Xcode p ...
- 用FineReport报表系统构建资金监管平台
一.应用背景 计算机的应用已经渗透到日常工作的许多方面,无论是其自身还是所发挥的作用,计算机都标志着一种高科技,使工作高效率和高水平.为了能更方便,更轻松,更好的管理,信息化建设正在日益发展壮大,更加 ...
- AC日记——配对碱基链 openjudge 1.7 07
07:配对碱基链 总时间限制: 1000ms 内存限制: 65536kB 描述 脱氧核糖核酸(DNA)由两条互补的碱基链以双螺旋的方式结合而成.而构成DNA的碱基共有4种,分别为腺瞟呤(A).鸟嘌 ...
- UIGrid/UITable 性能优化
性能优化 排行榜,邮件,关卡等数据列表项,一般在玩家打开面板时,都会重新刷新一次数据,那是否有必要每次都生成列表项呢? 假如每次列表的内容有变动就Instance 新的Gameobject,这是没有必 ...
- JAVA中遇到 UTF-八 序列的字节 1 无效
UTF-8 序列的字节 1 无效用dom4j操作xml文件, 出现了这个错误.原因是xml文件被创建的时候是ansi码格式. ( UTF-8 序列的字节 1 无效用dom4j操作xml文件, 出现 ...