[转]C#操作XML方法详解

本文转自:http://www.cnblogs.com/minotmin/archive/2012/10/14/2723482.html

using System.Xml;
//初始化一个xml实例
XmlDocument xml=new XmlDocument();

//导入指定xml文件
xml.Load(path);
xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));

//指定一个节点
XmlNode root=xml.SelectSingleNode("/root");

//获取节点下所有直接子节点
XmlNodeList childlist=root.ChildNodes;

//判断该节点下是否有子节点
root.HasChildNodes;

//获取同名同级节点集合
XmlNodeList nodelist=xml.SelectNodes("/Root/News");

//生成一个新节点
XmlElement node=xml.CreateElement("News");

//将节点加到指定节点下,作为其子节点
root.AppendChild(node);

//将节点加到指定节点下某个子节点前
root.InsertBefore(node,root.ChildeNodes[i]);

//为指定节点的新建属性并赋值
node.SetAttribute("id","11111");

//为指定节点添加子节点
root.AppendChild(node);

//获取指定节点的指定属性值
string id=node.Attributes["id"].Value;

//获取指定节点中的文本
string content=node.InnerText;

//保存XML文件
string path=Server.MapPath("~/file/bookstore.xml");
xml.Save(path);
//or use :xml.Save(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));

二、具体实例

在C#.net中如何操作XML
需要添加的命名空间:
using System.Xml;

定义几个公共对象:
XmlDocument xmldoc ;
XmlNode xmlnode ;
XmlElement xmlelem ;

1,创建到服务器同名目录下的xml文件:


方法一:
xmldoc = new XmlDocument ( ) ;
//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null);
xmldoc.AppendChild ( xmldecl);

//加入一个根元素
xmlelem = xmldoc.CreateElement ( "" , "Employees" , "" ) ;
xmldoc.AppendChild ( xmlelem ) ;
//加入另外一个元素
for(int i=1;i<3;i++)
{

XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees>
XmlElement xe1=xmldoc.CreateElement("Node");//创建一个<Node>节点
xe1.SetAttribute("genre","李赞红");//设置该节点genre属性
xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性

XmlElement xesub1=xmldoc.CreateElement("title");
xesub1.InnerText="CS从入门到精通";//设置文本节点
xe1.AppendChild(xesub1);//添加到<Node>节点中
XmlElement xesub2=xmldoc.CreateElement("author");
xesub2.InnerText="候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmldoc.CreateElement("price");
xesub3.InnerText="58.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到<Employees>节点中
}
//保存创建好的XML文档
xmldoc.Save ( Server.MapPath("data.xml") ) ;

//
结果:在同名目录下生成了名为data.xml的文件,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
</Employees>


方法二:
XmlTextWriter xmlWriter;
string strFilename = Server.MapPath("data1.xml") ;

xmlWriter = new XmlTextWriter(strFilename,Encoding.Default);//创建一个xml文档
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Employees");

xmlWriter.WriteStartElement("Node");
xmlWriter.WriteAttributeString("genre","李赞红");
xmlWriter.WriteAttributeString("ISBN","2-3631-4");

xmlWriter.WriteStartElement("title");
xmlWriter.WriteString("CS从入门到精通");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("author");
xmlWriter.WriteString("候捷");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("price");
xmlWriter.WriteString("58.3");
xmlWriter.WriteEndElement();

xmlWriter.WriteEndElement();

xmlWriter.Close();
//
结果:
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
</Employees>

2,添加一个结点:

XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load(Server.MapPath("data.xml"));
XmlNode root=xmlDoc.SelectSingleNode("Employees");//查找<Employees>
XmlElement xe1=xmlDoc.CreateElement("Node");//创建一个<Node>节点
xe1.SetAttribute("genre","张三");//设置该节点genre属性
xe1.SetAttribute("ISBN","1-1111-1");//设置该节点ISBN属性

XmlElement xesub1=xmlDoc.CreateElement("title");
xesub1.InnerText="C#入门帮助";//设置文本节点
xe1.AppendChild(xesub1);//添加到<Node>节点中
XmlElement xesub2=xmlDoc.CreateElement("author");
xesub2.InnerText="高手";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("price");
xesub3.InnerText="158.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到<Employees>节点中
xmlDoc.Save ( Server.MapPath("data.xml") );

//
结果:在xml原有的内容里添加了一个结点,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="张三" ISBN="1-1111-1">
<title>C#入门帮助</title>
<author>高手</author>
<price>158.3</price>
</Node>
</Employees>

3,修改结点的值(属性和子结点):

XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );

XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点

foreach(XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
if(xe.GetAttribute("genre")=="张三")//如果genre属性值为“张三”
{
xe.SetAttribute("genre","update张三");//则修改该属性为“update张三”

XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历
{
XmlElement xe2=(XmlElement)xn1;//转换类型
if(xe2.Name=="author")//如果找到
{
xe2.InnerText="亚胜";//则修改
}
}
}
}
xmlDoc.Save( Server.MapPath("data.xml") );//保存。

//
结果:将原来的所有结点的信息都修改了,xml的内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="update张三" ISBN="1-1111-1">
<title>C#入门帮助</title>
<author>亚胜</author>
<price>158.3</price>
</Node>
</Employees>

4,修改结点(添加结点的属性和添加结点的自结点):
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );

XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点

foreach(XmlNode xn in nodeList)
{
XmlElement xe=(XmlElement)xn;
xe.SetAttribute("test","111111");

XmlElement xesub=xmlDoc.CreateElement("flag");
xesub.InnerText="1";
xe.AppendChild(xesub);
}
xmlDoc.Save( Server.MapPath("data.xml") );

//
结果:每个结点的属性都添加了一个,子结点也添加了一个,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4" test="111111">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
<flag>1</flag>
</Node>
<Node genre="李赞红" ISBN="2-3631-4" test="111111">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
<flag>1</flag>
</Node>
<Node genre="update张三" ISBN="1-1111-1" test="111111">
<title>C#入门帮助</title>
<author>亚胜</author>
<price>158.3</price>
<flag>1</flag>
</Node>
</Employees>

5,删除结点中的某一个属性:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );
XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes;
foreach(XmlNode xn in xnl)
{
XmlElement xe=(XmlElement)xn;
xe.RemoveAttribute("genre");//删除genre属性

XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历
{
XmlElement xe2=(XmlElement)xn1;//转换类型
if(xe2.Name=="flag")//如果找到
{
xe.RemoveChild(xe2);//则删除
}
}
}
xmlDoc.Save( Server.MapPath("data.xml") );

//]
结果:删除了结点的一个属性和结点的一个子结点,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node ISBN="2-3631-4" test="111111">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node ISBN="2-3631-4" test="111111">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node ISBN="1-1111-1" test="111111">
<title>C#入门帮助</title>
<author>亚胜</author>
<price>158.3</price>
</Node>
</Employees>

6,删除结点:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );
XmlNode root=xmlDoc.SelectSingleNode("Employees");
XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes;
for(int i=0;i<xnl.Count;i++)
{
XmlElement xe=(XmlElement)xnl.Item(i);
if(xe.GetAttribute("genre")=="张三")
{
root.RemoveChild(xe);
if(i<xnl.Count)i=i-1;
}
}
xmlDoc.Save( Server.MapPath("data.xml") );

//]
结果:删除了符合条件的所有结点,原来的内容:

<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="张三" ISBN="1-1111-1">
<title>C#入门帮助</title>
<author>高手</author>
<price>158.3</price>
</Node>
<Node genre="张三" ISBN="1-1111-1">
<title>C#入门帮助</title>
<author>高手</author>
<price>158.3</price>
</Node>
</Employees>

删除后的内容:
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
<Node genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</Node>
</Employees>

7,按照文本文件读取xml

System.IO.StreamReader myFile =new
System.IO.StreamReader(Server.MapPath("data.xml"),System.Text.Encoding.Default);
//注意System.Text.Encoding.Default

string myString = myFile.ReadToEnd();//myString是读出的字符串
myFile.Close();

三、高级应用

/*读取xml数据两种xml方式*/
<aaa>
<bb>something</bb>
<cc>something</cc>
</aaa>

<aaa>
<add key="123" value="321"/>
</aaa>

/*第一种方法*/
DS.ReadXml("your xmlfile name");
Container.DataItem("bb");
Container.DataItem("cc");
DS.ReadXmlSchema("your xmlfile name");

/*第二种方法*/
<aaa>
<add key="123" value="321"/>
</aaa>
如果我要找到123然后取到321应该怎么写呢?

using System.XML;
XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument();
xmlDoc.Load(@"c:/Config.xml");
XmlElement elem = xmlDoc.GetElementById("add");
string str = elem.Attributes["value"].Value


/*第三种方法: SelectSingleNode 读取两种格式的xml *---/
--------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<ConnectionString>Data Source=yf; user id=ctm_dbo;password=123</ConnectionString>
</appSettings>
</configuration>
--------------------------------------------------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(strXmlName);

XmlNode node=doc.SelectSingleNode("/configuration/appSettings/ConnectionString");
if(node!=null)
{
string k1=node.Value; //null
string k2=node.InnerText;//Data Source=yf; user id=ctm_dbo;password=123
string k3=node.InnerXml;//Data Source=yf; user id=ctm_dbo;password=123
node=null;
}

********************************************************************
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=yf; user id=ctm_dbo;password=123" />
</appSettings>
</configuration>
**--------------------------------------------------------------------**
XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add");
if(node!=null)
{
string k=node.Attributes["key"].Value;
string v=node.Attributes["value"].Value;
node=null;
}
*--------------------------------------------------------------------*
XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add");
if(node!=null)
{
XmlNodeReader nr=new XmlNodeReader(node);
nr.MoveToContent();
//检查当前节点是否是内容节点。如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。
nr.MoveToAttribute("value");
string s=nr.Value;
node=null;
}

尊重作者,转发请注明出处:http://www.cnblogs.com/minotmin
谢谢阅读,有错请指出,不甚感激。

 

 

转载于:https://www.cnblogs.com/freeliver54/archive/2013/03/18/2965470.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/360900.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Web应用程序体系结构– Spring MVC – AngularJs堆栈

Spring MVC和AngularJs共同为构建表单密集型Web应用程序提供了一个真正高效且吸引人的前端开发堆栈。在这篇博客文章中&#xff0c;我们将看到如何使用这些技术构建表单密集型Web应用程序&#xff0c;并将这种方法与其他方法进行比较可用选项。 可以在此github 存储库中找到功能…

HTML5基础一:常用布局标签

1、DTD声明&#xff1a; <!doctype html> 2、布局标签 <html> <head></head> <body> //头部标签 <header> <nav>导航栏标签</nav> </header>  <div> //自定义主区间 <section> <ruby>夼<rp>(&…

Antd Table树形展示,分页后有时候数据渲染不出的问题

项目场景&#xff1a; Antd V4版 网页端 问题描述&#xff1a; 使用Table树形使用Card onTabChange 切换tab&#xff0c;有时候数据渲染不出的问题 const paginationProps {Current: currentNumber,size: small,pageSize,total,onChange: (PageNumber) > this.getList(Pa…

Java 8函数式编程:延迟实例化

单例通常会延迟实例化自己&#xff0c;有时&#xff0c;如果对象足够重&#xff0c;则可以延迟实例化类字段。 通常&#xff0c;在走惰性路线时&#xff0c;getter方法&#xff08;或accessor &#xff09;必须具有一段代码&#xff0c;该代码块在返回对象之前检查对象是否已实…

ant-design官网打不开 , 需要用镜像地址打开

如果网络不好的时候ant-design 的官网很难打开的 &#xff0c;用下面的镜像地址就可以打开啦 ant-design 官网镜像地址: http://ant-design.gitee.io/index-cn ant-design-pro镜像地址&#xff1a; http://ant-design-pro.gitee.io/index-cn antd-mobile镜像地址&#xff1a; …

全排列函数、组合函数

1 1、求一个全排列函数&#xff1a;如p([1,2,3])输出&#xff1a; [123],[132],[213],[231],[321],[312]. 2、求一个组合函数如p([1,2,3])输出&#xff1a; [1],[2],[3],[1,2],[2,3],[1,3],[1,2,3] 这两问可以用伪代码。 void swap(int *a, int *b) //交换函数 {int tmp;tmp *a…

Java中的XSL转换:一种简单的方法

XSL转换 &#xff08;XSLT&#xff09;是将一个XML文档转换为另一个XML文档的强大机制。 但是&#xff0c;在Java中&#xff0c;XML操作相当冗长和复杂。 即使是简单的XSL转换&#xff0c;也必须编写几十行代码—如果需要适当的异常处理和日志记录&#xff0c;甚至可能还要写更…

修改html页面的title,可以自定义

方式一&#xff1a; document.getElementsByTagName(“title”)[0].innerText ‘需要设置的值’; document.title方式 经过测试&#xff0c;还可通过document.title 设置title的值。方式二 console.log(document.title); # 可以获取title的值。 document.title ‘需要设置的值…

.Net环境下的缓存技术介绍 (转)

摘要: 介绍缓存的基本概念和常用的缓存技术&#xff0c;给出了各种技术的实现机制的简单介绍和适用范围说明&#xff0c;以及设计缓存方案应该考虑的问题&#xff08;共17页&#xff09; 1 概念 1.1 缓存能解决的问题 性能——将相应数据存储起来以避免数据的重复创…

antd Datepicker组件报错 ——date.clone is not a function或者date1.isAfter is not a function

问题描述&#xff1a; antd Datepicker组件报错 ——date.clone is not a function或者date1.isAfter is not a function 原因分析&#xff1a; 在From中渲染默认值&#xff0c;一般数据请求拿到返回值存在异步&#xff0c;会晚于渲染&#xff0c;因此日期转换不能放在DatePi…

集成CDI和WebSockets

考虑尝试一个简单的Java EE 7原型应用程序&#xff0c;该应用程序涉及JAX-RS&#xff08;REST&#xff09;&#xff0c;WebSockets和CDI。 注意 &#xff1a;不想让它成为破坏者-但这篇文章主要讨论了我在尝试使用Web套接字和使用CDI作为“胶水”的REST&#xff08;在Java EE应…

【记】jQuery中的选择器:visible对visibility:hidden的处理

首先先介绍visibility这个CSS属性。 visibility用于表示该元素是否显示&#xff0c;其取值有&#xff1a; visible&#xff1a;设置对象可视。  hidden&#xff1a;设置对象隐藏。  collapse&#xff1a;主要用来隐藏表格的行或列&#xff0c;隐藏的行或列能够被其他内容是…

React - antd4 中在form中为Switch赋值无效

项目场景&#xff1a; React - antd4; From表单 问题描述&#xff1a; Switch赋初始值无效 # 解决方案&#xff1a; let newCheck {};if (propsForm.type switch) {newCheck {...newCheck,valuePropName: "checked"}}<Form.Itemkey{propsForm.id}name{propsF…

在实践中重试HTTP标头

Retry-After是鲜为人知的HTTP响应标头。 让我引用RFC 2616&#xff08;HTTP 1.1规范&#xff09;的相关部分&#xff1a; 14.37重试后 Retry-After响应标头字段可与503 &#xff08; 服务不可用 &#xff09;响应一起使用&#xff0c;以指示请求该客户端的服务预计无法使用多…

Java中连接字符串的最佳方法

最近有人问我这个问题–在Java中使用运算符连接字符串是否对性能不利&#xff1f; 这让我开始思考Java中连接字符串的不同方法&#xff0c;以及它们如何相互对抗。 这些是我要研究的方法&#xff1a; 使用运算符 使用StringBuilder 使用StringBuffer 使用String.concat() …

时间转换以及公式

moment(item.updatedAt).fromNow() ;//距离今天多久了moment&#xff08;&#xff09;获得今天、明天和昨天的日期 let today moment(new Date());let tomorrow moment(new Date()).add(1,days);let yesterday moment(new Date()).add(-1, days);后续遇到继续补充

只不过是R.java文件的特性-----出错信息:R.java was modified manually! Reverting to generated version!...

出错信息:R.java was modified manually! Reverting to generated version! 出错原因&#xff1a;今天在res下建立了一个drawable的文件夹存放图片资源----图片名为1.jpg 后来R.java文件就报错了&#xff1a;R.java was modified manually! Reverting to generated version! 看…

十大最常见的Java性能问题

Java性能是所有Java应用程序开发人员都关心的问题&#xff0c;因为快速使应用程序与使其正常运行同等重要。 史蒂文海恩斯&#xff08;Steven Haines&#xff09;使用他在Java性能问题上的个人经验得出的结论是&#xff0c; 大多数问题都有共同的根本原因 。 因此&#xff0c;作…

antd form 初始化时间

initialValue: moment(record.showTime, YYYY-MM-DD HH:mm:ss)