C# -- 使用XmlDocument或XDocument创建xml文件

使用XmlDocument或XDocument创建xml文件

需引用:System.Xml; System.Xml.Linq;

1.使用XmlDocument创建xml(入门案例)

 1         static void Main(string[] args)
 2         {
 3             //使用XmlDocument创建xml
 4             XmlDocument xmldoc = new XmlDocument();
 5             XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
 6             xmldoc.AppendChild(xmldec);
 7 
 8             //添加根节点
 9             XmlElement rootElement = xmldoc.CreateElement("school");
10             xmldoc.AppendChild(rootElement);
11 
12             //添加根节点下的子节点元素
13             XmlElement classElement = xmldoc.CreateElement("class");
14             rootElement.AppendChild(classElement);
15             XmlAttribute atrrClass = xmldoc.CreateAttribute("No");
16             atrrClass.Value = "1";
17             classElement.Attributes.Append(atrrClass);
18 
19             //添加子节点下的元素
20             XmlElement stuElement = xmldoc.CreateElement("student");
21             classElement.AppendChild(stuElement);
22             XmlAttribute attrStu = xmldoc.CreateAttribute("sid");
23             attrStu.Value = "20180101";
24             stuElement.Attributes.Append(attrStu);
25 
26             //保存文件
27             xmldoc.Save(@"d:\zzz\TestA.xml");
28             Console.WriteLine("创建xml文件ok!");
29             Console.ReadKey();
30 
31         }


使用XmlDocument创建的xml文件:

 

2. 使用XDocument创建xml(入门案例)

 1         static void Main(string[] args)
 2         {
 3             //使用XDocument创建xml
 4             System.Xml.Linq.XDocument xdoc = new XDocument();
 5             XDeclaration xdec = new XDeclaration("1.0", "utf-8", "yes");
 6             xdoc.Declaration = xdec;
 7 
 8             //添加根节点
 9             XElement rootEle = new XElement("school");
10             xdoc.Add(rootEle);
11 
12             //给根节点添加子节点
13             XElement classEle = new XElement("class");
14             XAttribute attrClass = new XAttribute("No", 1);
15             classEle.Add(attrClass);
16             rootEle.Add(classEle);
17 
18             //添加子节点下的元素
19             XElement stuEle = new XElement("student");
20             XAttribute atrStu = new XAttribute("sid", "20180101");
21             stuEle.Add(atrStu);
22             classEle.Add(stuEle);
23 
24             //保存文件
25             xdoc.Save("d:\\zzz\\TestB.xml");
26             Console.WriteLine("创建xml文件ok");
27             Console.ReadKey();
28         }

使用XDocument创建的Xml文件:

 

posted on 2018-10-17 09:19  在代码的世界里游走  阅读(3561)  评论(0编辑  收藏  举报