C#中的XML文件操作(一)

Create a New XML File Using XmlDocument

Here's the XML File:

1 <?xml version="1.0" encoding="utf-8"?>
2 <CategoryList>
3   <Category ID="01">
4     <MainCategory>XML</MainCategory>
5     <Description>This is a list my XML articles.</Description>
6     <Active>true</Active>
7   </Category>
8 </CategoryList>

Here's the code:

 1 XmlDocument xmlDoc = new XmlDocument();
 2 
 3 
 4         // Write down the XML declaration
 5         XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null); 
 6 
 7         // Create the root element
 8         XmlElement rootNode  = xmlDoc.CreateElement("CategoryList");
 9         xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); 
10         xmlDoc.AppendChild(rootNode);
11 
12         // Create a new <Category> element and add it to the root node
13         XmlElement parentNode  = xmlDoc.CreateElement("Category");
14 
15         // Set attribute name and value!
16         parentNode.SetAttribute("ID", "01");
17 
18         xmlDoc.DocumentElement.PrependChild(parentNode);
19 
20         // Create the required nodes
21         XmlElement mainNode  = xmlDoc.CreateElement("MainCategory");
22         XmlElement descNode  = xmlDoc.CreateElement("Description");
23         XmlElement activeNode  = xmlDoc.CreateElement("Active");
24 
25         // retrieve the text 
26         XmlText categoryText= xmlDoc.CreateTextNode("XML");
27         XmlText descText  = xmlDoc.CreateTextNode("This is a list my XML articles.");
28         XmlText activeText  = xmlDoc.CreateTextNode("true");
29 
30         // append the nodes to the parentNode without the value
31         parentNode.AppendChild(mainNode);
32         parentNode.AppendChild(descNode);
33         parentNode.AppendChild(activeNode);
34 
35         // save the value of the fields into the nodes
36         mainNode.AppendChild(categoryText);
37         descNode.AppendChild(descText);
38         activeNode.AppendChild(activeText);
39 
40         // Save to the XML file
41         xmlDoc.Save( Path);

 

 

 

转载于:https://www.cnblogs.com/pyffcwj/p/3328104.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值