• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#手动添加XML文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Xml;
 7 
 8 namespace ConsoleApplication7
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             //中心思想:先声明版本,再添加一个总节点,在总结点内添加小节点,再相应的小节点内添加相应的小小节点
15             //创建一个XML对象
16             XmlDocument doc = new XmlDocument();
17 
18             //创建第一行描述信息
19             XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
20 
21             //将第一行数据添加到文件中
22             doc.AppendChild(dec);
23 
24             //给文档添加根节点
25             XmlElement Books = doc.CreateElement("Books");
26             //将根节点添加给文档对象
27             doc.AppendChild(Books);
28 
29             //给文档添加根节点
30             XmlElement book1 = doc.CreateElement("Book");
31             //将子节点book1添加到根节点下
32             Books.AppendChild(book1);
33             //给book1添加子节点
34             XmlElement bookname = doc.CreateElement("BookName");
35             //设置标签内的显示的文本
36             bookname.InnerText = "水浒传";

//
bookname.InnerText = "<a>水浒传"<a>;此处会把“<”“>”进行转义
// bookname.InnerXml = "<a>水浒传"<a>;此处不会把“<”“>”进行转义

//
bookname.setAttribute(string name,string value)对标签设置属性
37 //添加子节点 38  book1.AppendChild(bookname); 39 40 XmlElement author = doc.CreateElement("Author"); 41 author.InnerText = "水浒传的作者"; 42  book1.AppendChild(author); 43 44 45 XmlElement price = doc.CreateElement("Price"); 46 price.InnerText = "1000元"; 47  book1.AppendChild(price); 48 49 XmlElement book2 = doc.CreateElement("Book"); 50  Books.AppendChild(book2); 51 52 XmlElement bookname2 = doc.CreateElement("BookName"); 53 bookname2.InnerText = "西游记"; 54  book2.AppendChild(bookname2); 55 XmlElement author1 = doc.CreateElement("Author"); 56 author1.InnerText = "西游记的作者"; 57  book2.AppendChild(author1); 58 XmlElement price2 = doc.CreateElement("Price"); 59 price2.InnerText = "2000元"; 60  book2.AppendChild(price2); 61 62 63 64 //保存XML文件 65 doc.Save("a.xml"); 66 Console.WriteLine("保存成功"); 67  Console.ReadKey(); 68 69  } 70  } 71 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#在异常中获取HttpStatusCode用法发布时间:2022-07-10
下一篇:
C#格式化输出发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap