.net中XML的创建01(传统方法)
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>
最新文章
- UVA103 dp基础题,DAG模型
- C++ 中堆栈学习
- 通过反射获取父类泛型的Class对象 ParameterizedType
- JAVA 注解的几大作用及使用方法详解【转】
- ADO.NET 快速入门(四):从数据库填充 DataSet
- 02-测试、文件读写、xml解析
- Ubuntu14.04(64位)安装ATI_Radeon_R7_M265显卡驱动
- 团队作业8----第二次项目冲刺(Beta阶段) 第四天
- [AHOI 2016初中组]自行车比赛
- UE4使用C++创建枚举变量适用于C++与蓝图
- Windows10上搭建Kinect 2 开发环境
- [Swift]LeetCode766. 托普利茨矩阵 | Toeplitz Matrix
- java网络编程小白教程
- java面试总结(资料来源网络)
- does not support SSL connections
- postman进行接口测试
- ZooKeeper 典型的应用场景——及编程实现
- [Deep-Learning-with-Python]基于Keras的房价预测
- LPDMvvmKit 系列之 UITableView 的改造
- 通过Java 线程堆栈进行性能瓶颈分析
热门文章
- HYPER-V2008里安装WINDOWS 2012,以及监控宝
- javascript类型系统之Array
- android如何获取默认的桌面程序
- 【贪心】HDU 5783 Divide the Sequence
- Remove Duplicates from Sorted List II ——LeetCode
- Nodejs in Visual Studio Code 14.IISNode与IIS7.x
- MYSQL: Cannot delete or update a parent row: a foreign key constraint fails
- Swing实现文件选择(目录选择)附导出
- freemarker入门教程
- 使用国人的koala来重新预编译BOOTSTRAP的LESS文件