吴旭晓个人博客 繁体中文 简体中文

首页| 日志 |JAVA |ASP |PHP |Android |IOS |ASP.NET |JavaScript |DIV+CSS |SEO |taobaoke |饼哥语录
繁体中文 简体中文

c#.net创建xml文件

问题:我们如何生成如下xml文档?

[xhtml] view plaincopyprint?
  1. <?xml version="1.0" encoding="gb2312"?>  
  2. <Employees>  
  3.   <Node genre="李赞红" ISBN="2-3631-4">  
  4.     <title>CS从入门到精通</title>  
  5.     <author>候捷</author>  
  6.     <price>58.3</price>  
  7.   </Node>  
  8.   <Node genre="李赞红" ISBN="2-3631-4">  
  9.     <title>CS从入门到精通</title>  
  10.     <author>候捷</author>  
  11.     <price>58.3</price>  
  12.   </Node>  
  13. </Employees>  

实现方法如下:

visul studio 2008下测试通过

//创建好的文件保存在c:/data.xml中

 

[c-sharp] view plaincopyprint?
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Xml;  
  6.   
  7. namespace CreatXML  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             XmlDocument xmldoc;  
  14.             XmlNode xmlnode;  
  15.             XmlElement xmlelem;  
  16.   
  17.             xmldoc = new XmlDocument();  
  18.             //加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>   
  19.             XmlDeclaration xmldecl;  
  20.             xmldecl = xmldoc.CreateXmlDeclaration("1.0""gb2312"null);  
  21.             xmldoc.AppendChild(xmldecl);  
  22.   
  23.             //加入一个根元素   
  24.             xmlelem = xmldoc.CreateElement("""Employees""");  
  25.             xmldoc.AppendChild(xmlelem);  
  26.             //加入另外一个元素   
  27.             for (int i = 1; i < 3; i++)  
  28.             {  
  29.   
  30.                 XmlNode root = xmldoc.SelectSingleNode("Employees");//查找<Employees>    
  31.                 XmlElement xe1 = xmldoc.CreateElement("Node");//创建一个<Node>节点    
  32.                 xe1.SetAttribute("genre""李赞红");//设置该节点genre属性    
  33.                 xe1.SetAttribute("ISBN""2-3631-4");//设置该节点ISBN属性    
  34.   
  35.                 XmlElement xesub1 = xmldoc.CreateElement("title");  
  36.                 xesub1.InnerText = "CS从入门到精通";//设置文本节点    
  37.                 xe1.AppendChild(xesub1);//添加到<Node>节点中    
  38.                 XmlElement xesub2 = xmldoc.CreateElement("author");  
  39.                 xesub2.InnerText = "候捷";  
  40.                 xe1.AppendChild(xesub2);  
  41.                 XmlElement xesub3 = xmldoc.CreateElement("price");  
  42.                 xesub3.InnerText = "58.3";  
  43.                 xe1.AppendChild(xesub3);  
  44.   
  45.                 root.AppendChild(xe1);//添加到<Employees>节点中    
  46.             }  
  47.             //保存创建好的XML文档   
  48.             xmldoc.Save("c:/data.xml");   
  49.         }  
  50.     }  
  51. }  

作者:吴旭晓 | 来源:个人网站 | 点击量:1478 | 发布时间:2013-12-04
最新留言 | 返回上一页 | 返回首页

相关文章:

版权所有:吴旭晓个人博客 Copyright © 2013-2023 个人博客