XML传统的创建:

  传统的创建主要是依据XmlDocument的对象展开的,通过XmlDocument对象可以创建元素(XmlElement)、属性(XmlAttribute)以及文本节点(CreateTextNode)

  具体实例:

  XML:

  1-> 创建XmlDocument和描述,并添加描述:

    XmlDocument xml=new XmlDocument();

    XmlDeclaration xmldec = xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);

    xml.AppendChild(xmldec);

  2->创建根节点,并添加到xml中,根节点只能有一个

    XmlElement root = xml.CreateElement("root");

    xml.AppendChild(root);

  3->准备数据,循环该数据集合,并创建XmlElement元素节点及相关属相

    List<Student> list = new List<Student>(){

      new Student(){Name="张三",Gender="男",Age=17},

      new Student(){Name="李四",Gender="男",Age=21},

      new Student(){Name="王五",Gender="男",Age=19}
    };

    //循法集合中的对象

for (int i = 0; i < list.Count(); i++)
{

//创建stu节点并添加属性id

XmlElement stu = xml.CreateElement("Student");//用XmlDocument的实例xml创建元素
XmlAttribute id = xml.CreateAttribute("id");//用XmlDocument的实例xml创建属性
id.Value = "00" + (i+1);//为属性赋值
stu.Attributes.Append(id);//将属性id添加到stu的属性集合中去

//创建name节点并复制。然后追加到stu节点下

XmlElement name = xml.CreateElement("Name");//用XmlDocument的实例xml创建元素

name.AppendChild(xml.CreateTextNode(list[i].Name));//为元素创建TextNode,并赋值
stu.AppendChild(name); //将name节点添加到stu节点下

//创建age 节点并复制。然后追加到stu节点下

XmlElement age = xml.CreateElement("Age");
age.AppendChild(xml.CreateTextNode(list[i].Age.ToString()));
stu.AppendChild(age);

//创建gender 节点并复制。然后追加到stu节点下

XmlElement gender = xml.CreateElement("Gender");
gender.AppendChild(xml.CreateTextNode(list[i].Gender));
stu.AppendChild(gender);

//将stu节点追加到跟节点root下
root.AppendChild(stu);

}

  4->保存XML文件

     xml.Save("xxx.xml");

  5->最终生成的XML

<?xml version="1.0" encoding="gb2312"?>
<root>

  <Student id="001">
    <Name>张三</Name>
    <Age>17</Age>
    <Gender>男</Gender>
  </Student>

  <Student id="002">
    <Name>李四</Name>
    <Age>21</Age>
    <Gender>男</Gender>
  </Student>

  <Student id="003">
    Name>王五</Name>
    <Age>19</Age>
    <Gender>男</Gender>
  </Student>

</root>

  

  

最新文章

  1. UVA103 dp基础题,DAG模型
  2. C++ 中堆栈学习
  3. 通过反射获取父类泛型的Class对象 ParameterizedType
  4. JAVA 注解的几大作用及使用方法详解【转】
  5. ADO.NET 快速入门(四):从数据库填充 DataSet
  6. 02-测试、文件读写、xml解析
  7. Ubuntu14.04(64位)安装ATI_Radeon_R7_M265显卡驱动
  8. 团队作业8----第二次项目冲刺(Beta阶段) 第四天
  9. [AHOI 2016初中组]自行车比赛
  10. UE4使用C++创建枚举变量适用于C++与蓝图
  11. Windows10上搭建Kinect 2 开发环境
  12. [Swift]LeetCode766. 托普利茨矩阵 | Toeplitz Matrix
  13. java网络编程小白教程
  14. java面试总结(资料来源网络)
  15. does not support SSL connections
  16. postman进行接口测试
  17. ZooKeeper 典型的应用场景——及编程实现
  18. [Deep-Learning-with-Python]基于Keras的房价预测
  19. LPDMvvmKit 系列之 UITableView 的改造
  20. 通过Java 线程堆栈进行性能瓶颈分析

热门文章

  1. HYPER-V2008里安装WINDOWS 2012,以及监控宝
  2. javascript类型系统之Array
  3. android如何获取默认的桌面程序
  4. 【贪心】HDU 5783 Divide the Sequence
  5. Remove Duplicates from Sorted List II ——LeetCode
  6. Nodejs in Visual Studio Code 14.IISNode与IIS7.x
  7. MYSQL: Cannot delete or update a parent row: a foreign key constraint fails
  8. Swing实现文件选择(目录选择)附导出
  9. freemarker入门教程
  10. 使用国人的koala来重新预编译BOOTSTRAP的LESS文件