C#Xml的三种创建方式(或者是两种?)和增删改查
一.Xml的创建方式
-
- Xmlwriter(流式读取,Stream)
写过了:https://www.cnblogs.com/dengzhekaihua/p/15438493.html 这种方法虽然快,但是只能写一遍,一次性全部写完,不方便进行修改
2.通过Xelement直接写xml(Linq to xml)
- Xmlwriter(流式读取,Stream)
点击查看代码
XElement xElement = new XElement(
new XElement("ProductType",
new XElement("BMW",
new XElement("Threshold", "Search", new XAttribute("Max", 100)),//后面这个是obj类型,写啥都行,输出的时候XAttribute.Value都是string类型
new XElement("Threshold", "Search", new XAttribute("Min", "20")),
new XElement("ROI", "Rect1"),
new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
),
new XElement("Volvo",
new XElement("Threshold", "Search", new XAttribute("Max", 100)),
new XElement("Threshold", "Search", new XAttribute("Min", "20")),
new XElement("ROI", "Rect2"),
new XElement("Date", DateTime.Now.ToString("yyyy-MM-dd"))
)));
string iniPath = Application.StartupPath + "\\params";
string xmlPath = iniPath + "\\ProductInfo.xml";
//需要指定编码格式,否则在读取时会抛:根级别上的数据无效。 第 1 行 位置 1异常
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.Indent = true;
XmlWriter xw = XmlWriter.Create(xmlPath, settings);//不用xmlwriter 用document写也一样的,但是writer快一点
xElement.Save(xw);
xw.Flush();
xw.Close();
点击查看代码
//使用XDocument创建xml
System.Xml.Linq.XDocument xdoc = new XDocument();
XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
xdoc.Declaration = xdec;
//添加根节点
XElement rootEle = new XElement("school");
xdoc.Add(rootEle);
//给根节点添加子节点
XElement classEle = new XElement("class");
XAttribute attrClass = new XAttribute("No", 1);
classEle.Add(attrClass);
rootEle.Add(classEle);//其实就是看哪个Xelement.Add的,哪个加的哪个就是谁的子节点
XElement classEle1 = new XElement("class1");
XAttribute attrClass1 = new XAttribute("No", 1);
classEle1.Add(attrClass1);
rootEle.Add(classEle1);
//添加子节点下的元素
XElement stuEle = new XElement("student");
XAttribute atrStu = new XAttribute("sid", "20180101");
stuEle.Add(atrStu);
classEle.Add(stuEle);
//保存文件
xdoc.Save("d:\\zzz\\TestB.xml");
XDocument 属性
三.Xml的增加
1.可以用上面第三种里面的XElement.Add()去添加节点到对应的位置
//没写完
分类:
c#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix