C# 读写XML文件实例代码
作者:OmySql 发布时间:2023-04-01 03:40:58
标签:C#,读写XML
C#史上最简单读写xml文件方式,创建控制台应用程序赋值代码,就可以运行,需要改动,请自行调整
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace ConsoleApp1
{
class Program
{
public const String xmlPath = "info.xml";
static void Main(string[] args)
{
IDictionary<String, List<String>> infos = new Dictionary<String, List<String>>();
infos.Add("Evan", new List<string>() { "123", "456" });
SaveXML(infos);
ReadXML();
Console.ReadKey();
}
public static void SaveXML(IDictionary<String, List<String>> infos)
{
if (infos == null || infos.Count == 0)
{
return;
}
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(dec);
XmlElement _infos = xmlDoc.CreateElement("infos");
foreach (KeyValuePair<String, List<String>> item in infos)
{
XmlElement info = xmlDoc.CreateElement("info");
XmlElement name = xmlDoc.CreateElement("file1");
name.InnerText = item.Key;
info.AppendChild(name);
XmlNode filelist = xmlDoc.CreateElement("filelist");
info.AppendChild(filelist);
foreach (String number in item.Value)
{
XmlElement filed = xmlDoc.CreateElement("filed");
filed.InnerText = number;
filelist.AppendChild(filed);
}
_infos.AppendChild(info);
}
xmlDoc.AppendChild(_infos);
xmlDoc.Save(xmlPath);
}
public static IDictionary<String, List<String>> ReadXML()
{
IDictionary<String, List<String>> infos = new Dictionary<String, List<String>>();
if (File.Exists(xmlPath))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPath);
XmlNode xn = xmlDoc.SelectSingleNode("infos");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl)
{
XmlElement xe = (XmlElement)xnf;
XmlNode nameNode = xe.SelectSingleNode("file1");
string name = nameNode.InnerText;
Console.WriteLine(name);
XmlNode filelist = xe.SelectSingleNode("filelist");
List<String> list = new List<string>();
foreach (XmlNode item in filelist.ChildNodes)
{
list.Add(item.InnerText);
}
infos.Add(name, list);
}
}
return infos;
}
}
}
内容扩展:
实例代码
dim domxmldocument as system.xml.xmldocument
dim tmppath as string = apptempfilepath
dim xmlfile as string = tmppath + "\testxml.xml"
'窗体加载事件
private sub testxml_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load
'读xml过程测试通过
dim domxmldocument as system.xml.xmldocument
dim tmppath as string = apptempfilepath
dim xmlfile as string = tmppath + "\testxml.xml"
dim reader as system.xml.xmlreader = nothing
try
reader = new xml.xmltextreader(xmlfile)
'reader.
while reader.read
me.lboxxml.items.add(reader.name + reader.value)
end while
catch ex as exception
msgbox(ex.message)
finally
if not (reader is nothing) then
reader.close()
end if
end try
end sub
'载入xml事件
private sub btnxmlload_click(byval sender as system.object, byval e as system.eventargs) handles btnxmlload.click
'me.lboxxml.items.clear()
''读xml过程测试通过
'dim reader as system.xml.xmlreader = nothing
'try
' reader = new xml.xmltextreader(xmlfile)
' while reader.read
' me.lboxxml.items.add(reader.name + ":" + reader.value)
' end while
'catch ex as exception
' msgbox(ex.message)
'finally
' if not (reader is nothing) then
' reader.close()
' end if
'end try
dim ds as new dataset
try
'如果直接使用ds做datasource则不会展开datagrid,用dv则能直接显示正确。
ds.readxml(xmlfile)
dim tb as datatable
dim dv as dataview
tb = ds.tables(0)
dv = new dataview(tb)
datagrid1.datasource = dv
'datagrid1.datamember = "testxmlmember"
'datagrid1.datamember = "employeefname"
'dim dxd as new xmldatadocument
catch ex as exception
msgbox(ex.message.tostring)
end try
end sub
'保存新建xml内容事件
private sub btnsavenew_click(byval sender as system.object, byval e as system.eventargs) handles btnsavenew.click
dim mytw as new xmltextwriter(tmppath + "\testxmlwrite.xml", nothing)
mytw.writestartdocument()
mytw.formatting = formatting.indented
mytw.writestartelement("team")
mytw.writestartelement("player")
mytw.writeattributestring("name", "george zip")
mytw.writeattributestring("position", "qb")
mytw.writeelementstring("nickname", "zippy")
mytw.writeelementstring("jerseynumber", xmlconvert.tostring(7))
mytw.writeendelement()
mytw.writeendelement()
mytw.writeenddocument()
mytw.close()
end sub
文件很大的情况下,可以考虑手动实现数据更新适配器,比如手动实现一个xml节点搜索/更新,这样就不用重写整个xml。
如果程序的i/o不是主要问题,还是用实体类整个的写入更新吧,毕竟数据的完整性是第一位的。
如是文章类的,对该目录建一个xml索引文件来存放文章的编号,url等,用xml的attribute作为标记不同字段,内容页面可以用另外的html或xml页面存放,用linq to xml操作数据,效率不是很差,个人观点。当搜索时候只要查询指定文件名xml或文件类型就可以了。
来源:https://www.cnblogs.com/OmySql/p/12405569.html


猜你喜欢
- 前言项目里有个功能,在应用内切换语言,之前上线了大半年,一直都是正常运行,但是最近这次发版以后,在国外的同事反馈(这里面还包括CEO...
- 一、前言最近写了个项目,前端还没写,需要部署到服务器给女朋友实现前端,可是不熟悉Linux的我,蹑手蹑脚,真的是每一步都是bug,可谓是步步
- 安装方式:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可。先说说DTODTO是个什么东东?DTO
- 本文实例讲述了Java线程池用法。分享给大家供大家参考,具体如下:一 使用newSingleThreadExecutor创建一个只包含一个线
- 一. 安装依赖包yum install -y wgetyum install -y gcc-c++yum install -y zlib-d
- 类加载所有类加载器,都是ClassLoader的子类。类加载器永远以.class运行的目录为准。读取classpath根目录下的文件有以下几
- 关于 LoadLibrary 的疑问Win32 API 中 LoadLibrary 函数的功能是加载某个库文件(通常是 dll 文件),然后
- 本文实例为大家分享了toolabar结合drawlayout使用方法,供大家参考,具体内容如下package alice.bw.com.da
- TreeWidget 目录树组件,该组件适用于创建和管理目录树结构,在开发中我们经常会把它当作一个升级版的ListView组件使用,因为Li
- @Aspect@Order各个通知的执行顺序两个切面类:【记录日志】和【判断参数】,分别对应顺序 @Order(0) 和@Order(1)
- 事发地原默认的Feign是使用URLConnector进行通信的,当换为okhttp时,直接引入包及配置以下内容根本不生效,还是走原生的。f
- 本文实例为大家分享了Android EventBus普通事件和粘性事件,供大家参考,具体内容如下展示效果 添加EventBus导入依赖com
- java多线程之CyclicBarrier的使用方法public class CyclicBarrierTest { public stat
- 前言Windows 11下所有控件已经默认采用圆角,其效果更好、相对有着更好的优化,只是这是默认的行为,无法进一步自定义。注意两点:Pain
- Android 实现记住用户名和密码的功能是通过SharedPreference 存储来实现的。创建一个复选按钮,通过按钮的否选取来进行事件
- 本文实例为大家分享了C#生成Word文件的具体代码,供大家参考,具体内容如下通过Microsoft.Office.Interop.Word生
- 通过微软的SAPI,不仅仅可以实现语音合成TTS,同样可以实现语音识别SR。下面我们就介绍并贴出相关代码。主要有两种方式:1、使用COM组件
- 1.Action中的validate()方法Struts2提供了一个Validateable接口,这个接口中只存在validat
- Spring Boot是什么众所周知 Spring 应用需要进行大量的配置,各种 XML 配置和注解配置让人眼花缭乱,且极容易出错,因此 S
- 接口介绍:识别超过9千种菜品,支持客户创建属于自己的菜品图库,可准确识别图片中的菜品名称、位置、卡路里信息,并获取百科信息,适用于多种客户识