首页 > 技术文章 > C#中的XML文件操作(一)

pyffcwj 2013-09-18 11:20 原文

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);

 

 

 

推荐阅读