<pre name="code" class="plain">
在.net中经由过程XmlDocument与XDocument体式格局也能够写入XML个中XmlDocument是本来支撑的规范的XML写入类,如今扩大的XDocument类运用越发轻易,下面用XDocument类来写入一个XML文件。
写入步骤:
(1)起首建立一个XDocument对象
(2)设置XML的文档定义
(3)建立根节点
(4)轮回list鸠合建立子节点(这里用的是person类来录入数据)
(5)保存到文件
</pre><pre code_snippet_id="1703485" snippet_file_name="blog_20160531_9_7405027" name="code" class="csharp"> <pre name="code" class="csharp"> List<person> list = new List<person>(); <span style="font-family:Microsoft YaHei;font-size:18px;"> list.Add(new person() { name = "IstarI", age = 20, Email = "1061399756@qq.com" }); list.Add(new person() { name = "Orange", age = 20, Email = "521@qq.com" }); //1、建立一个XDocument对象 XDocument xDoc = new XDocument(); XDeclaration XDec = new XDeclaration("1.0", "utf-8","no"); //设置xml的文档定义 xDoc.Declaration = XDec; //2、建立根节点 XElement rootElement = new XElement("List"); xDoc.Add(rootElement); //3、轮回list鸠合建立子节点 for (int i = 0; i <list.Count; i++) { //为每一个person对象建立一个person元素 XElement xpersonElement = new XElement("person"); xpersonElement.SetAttributeValue("id", (i + 1).ToString()); xpersonElement.SetElementValue("name", list[i].name); xpersonElement.SetElementValue("age", list[i].age.ToString ()); xpersonElement.SetElementValue("Email", list[i].Email); rootElement.Add(xpersonElement); } //4、保存到文件 xDoc.Save("List1.xml"); MessageBox.Show("OK");</span>
写入终了后在Debug下就会涌现这个文件,然后翻开它就会看到本身想要的效果。
以上就是XML(2)经由过程XmlDocument与XDocument体式格局写入XML的内容,更多相关内容请关注ki4网(www.ki4.cn)!