.net 操作XML小结

C#操作XML时,对xmlNode增、删、改操作 立即下载
 

一、简单介绍

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/dreamof/archive/2008/08/14/1268096.html

ArcGIS License Server点击启动没反应,许可管理器无法启动怎么办 4 当我们再打开ArcGIS License Server Administrator的时候。3 在【服务】中找到【ArcGIS License Manager】双击。无法启动ArcGIS License Server的情况。在使用ArcGIS的过程中,我们经常会遇到。专注GIS领域知识分享,交流行业软件技巧。欢迎关注,不定期分享GIS各种问题和技巧。1 右击我的电脑——【管理】服务状态——启动,确定即可。启动类型选择——自动。 阅读详情

相关推荐

温度实时检测预警系统(STC89C51RC+DS18B20)

温度实时检测预警系统

1 兴趣 2 实践 1494

.Net 操作XML文件!!

 一、简单介绍using System.Xml;//初始化一个xml实例XmlDocument xml=new XmlDocument();//导入指定xml文件xml.Load(path);xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));//指定一个节点XmlNode r

780

时空数据建模的跨节点联邦图神经网络:KDD21 Cross-Node Federated Graph Neural Network for Spatio-Temporal Data Modeling

前言 联邦学习(FL)虽然已经被广泛研究,但是对复杂的时空依赖关系进行建模以提高预测能力仍然是一个开放的问题。此外目前最优的时空预测模型假定对数据的访问不受限制,忽略了对数据共享的限制。基于此,本文提了一个基于图联邦学习的时空数据模型 Cross-Node Federated Graph Neural Network (CNFGNN),该模型在跨节点联邦学习的约束下,使用基于图神经网络(GNN)的架构对底层图结构进行编码,属于结构化联邦的一种,每个本地模型利用私有数据进行学习,并保持分散性。CNFGNN

qq_56027260的博客 1810

C#判断节点下是否还有子节点的方法

转载自:http://blog.csdn.net/challeng_everything/article/details/43970811 自己稍微有点修正、整理,望原作者见谅,谢谢。 理论上来说 C# 的 XmlNode 类提供的 ChildNodes 以及 HasChildNodes 属性可以判断是否存在子节点。 但是在有 InnerText 的情况下,无论是 ChildNodes....

善战者无赫赫之功 的专栏 2719

从零开始理解异构算力调度:全国一体化算力算网平台实战解析

本文深入解析了异构算力调度技术在全国一体化算力算网平台中的实战应用。通过资源抽象层设计、动态感知引擎和跨云调度算法,实现AI训练任务的高效资源分配,显著提升计算效率并降低成本。特别针对GPU等异构算力的智能调度方案,为多云协同环境下的AI开发提供实用指南。

weixin_28730927的博客 332

基于STM32、HAL库的IP2736U_EF快充协议芯片简介及驱动程序设计

@param connected: 连接状态指针 (1=已连接, 0=未连接)= 0x2736) // 检查厂商ID。* @param hip: IP2736U句柄指针。* @param hip: IP2736U句柄指针。* @param hip: IP2736U句柄指针。* @param hip: IP2736U句柄指针。* @param hip: IP2736U句柄指针。* @param hip: IP2736U句柄指针。* @param hip: IP2736U句柄指针。

corlin6688的博客 429

C# xml文件读取与修改

c#读写xml文件已知有一个XML文件(bookstore.xml)如下: Code<?xml version="1.0" encoding="gb2312"?><bookstore> <book genre="fantasy" ISBN="2-3631-4"> <title>Oberon's Legacy</title...

baodie0806的博客 422

RK3588开发笔记-5G模块(SIM8200、广和通FM160、移远RM500U)调试笔记

RK3588 CPU提供了丰富的外设接口,本文主要介绍通过usb3.0接口驱动5G模块来实现5g无线数据传输功能。在物联网和边缘计算领域,5G网络支持的高速率、低延时连接为应用带来了更多可能性。RK3588作为一款高性能SoC,适合用于5G联网应用。SIM8200广和通FM160和移远RM500U。在RK3588上调试5G模块可以为设备提供稳定的高速联网能力。本文介绍了如何配置和调试SIM8200、广和通FM160和移远RM500U模块,通过AT指令和QMI/MBIM工具实现5G数据连接。

flypig has a dream! 2669

C#:xmldocument 如何 释放文件资源,释放存储空间?

转载地址:https://ask.zol.com.cn/x/5903981.html XmlDocument是托管资源 不需要你主动释放 一般需要主动释放的对象都会提供Close或者Dispose方法

波波诸葛伟 1059

置顶必读(1) | 滚雪球学Oracle教程导航帖,带你弯道超车(持续更新中)

什么是数据库管理系统(DBMS),Oracle在行业中的领先地位Oracle数据库的市场竞争与主要应用场景Oracle数据库的核心功能模块与未来技术发展趋势约束的高级应用:主键、唯一性、外键设计与管理表分区、视图、同义词与序列的最佳实践PL/SQL编程的设计哲学,如何高效使用Oracle SQL DeveloperPL/SQL代码调试与优化技巧RAC集群中的高可用性设计,负载均衡与并行查询的配置集群中的缓存一致性管理。

**My Coding Family** 1万+

Python 爬虫实战:破解网页 JS 混淆加密参数

摘要:本文针对Python爬虫破解JS混淆加密参数的技术难题,系统解析了变量混淆、控制流混淆、AES/MD5加密混淆等常见类型及其检测方法,提出"定位-还原-复现"的三步破解策略。通过实战案例详细演示了从JS逆向分析到Python代码实现的完整流程,包括MD5签名生成、AES加密复现等核心代码实现,并对不同混淆场景的破解方法进行了对比分析。文中特别强调技术应用的合规性边界,指出开发者应遵守相关法律法规,在合理范围内使用逆向技术。随着反爬技术升级,建议开发者持续学习动态调试等进阶技能,同时

2503_91057718的博客 2063

net 操作XML小结

一、简单介绍 using System.Xml; //初始化一个xml实例 XmlDocument xml=new XmlDocument(); //导入指定xml文件 xml.Load(path); xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); //指定一个节点 XmlNode ro

zjlovety的专栏 483

基于Playwright与异步技术的公司评价智能爬取实战:以Glassdoor为例

本文将介绍一套基于最新Python技术的智能爬虫解决方案,使用Playwright实现浏览器自动化,结合异步编程和智能解析技术,高效抓取Glassdoor等平台的公司评价数据。我们不仅关注数据获取,更注重数据的结构化处理和反反爬虫策略的实现。

2201_76125261的博客 223

.net操作xml小结

一、简单介绍 using System.Xml; //初始化一个xml实例 XmlDocument xml=new XmlDocument(); //导入指定xml文件 xml.Load(path); xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); //指定一个节点 XmlN

ATCO[这里,只是顺手插曲] 546

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

.net操作xml小结————《一》

<br /> XmlDocument    docu  = new  XmlDocument();是xml的文档对象<br />XmlElement element = docu .DocumentElement;//得到所有的xml元素<br />XmlNodeList  nodeList =  element .SelectNodes(“/加工贸易报文/报文体/申报数据/原地转型主要内容”);//根据节点找子节点<br /> <br />//第一个参数:父节点的位置;第二个参数:要找的节点;第三个参数:

fengchao1000的专栏 488

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

上一篇: 网页页面中的区域控制 (document.body与window.screen)
下一篇: ASP.NET中页面传值
ArvinStudy
博客等级 码龄15年 83粉丝 193原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值