Create XML using class XmlDocument

本文介绍了一个使用C#创建XML文档的例子,包括定义XML声明、创建根节点及子节点,并设置属性和文本内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 The result XML document is as follows:

  1. <?xml version="1.0" encoding="GB2312"?>
  2. <Books>
  3.   <Book genre="Mystery" publicationdate="2001" ISBN="123456789">
  4.     <title>The Case of the Missing Cookie</title>
  5.     <author Country="America">
  6.       <Name>Cookie Monster</Name>
  7.     </author>
  8.     <Price>$9.99</Price>
  9.   </Book>
  10. </Books>

The C# code is:

  1. XmlDocument xmlDoc = new XmlDocument();
  2.             // Create XML declaration
  3.             XmlDeclaration xdl = xmlDoc.CreateXmlDeclaration("1.0""GB2312"null);
  4.             xmlDoc.AppendChild(xdl);
  5.             // Create root node "Books"
  6.             XmlElement books = xmlDoc.CreateElement("Books");
  7.             // Create child node book infomation
  8.             XmlElement book1 = xmlDoc.CreateElement("Book");
  9.             // set node attributes
  10.             book1.SetAttribute("genre""Mystery");
  11.             book1.SetAttribute("publicationdate""2001");
  12.             book1.SetAttribute("ISBN""123456789");
  13.             // create sub elements for book
  14.             XmlElement title = xmlDoc.CreateElement("title");
  15.             title.InnerText = "The Case of the Missing Cookie";
  16.             book1.AppendChild(title);
  17.             XmlElement author = xmlDoc.CreateElement("author");
  18.             author.SetAttribute("Country""America");
  19.             book1.AppendChild(author);
  20.             XmlElement authorName = xmlDoc.CreateElement("Name");
  21.             authorName.InnerText = "Cookie Monster";
  22.             author.AppendChild(authorName);
  23.             XmlElement price = xmlDoc.CreateElement("Price");
  24.             price.InnerText = "$9.99";
  25.             book1.AppendChild(price);
  26.             // add book information to books which is root element of the document
  27.             books.AppendChild(book1);
  28.             // add root node to document
  29.             xmlDoc.AppendChild(books);
  30.             // save the xml document to file system
  31.             xmlDoc.Save("d://file1.xml");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值