xml操作(二)添加xml节点的子节点

来源:互联网 发布:db2和oracle的sql区别 编辑:程序博客网 时间:2024/05/16 18:40

一显示效果




二 代码

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Xml;namespace CsharpConsoleApplication{    class Program    {        static void Main(string[] args)        {            int i = 0;            HOSPITAL hosp = new HOSPITAL() { HospId = 1, HospName ="中医院"};            hosp.listDept = new List<DEPT>();            hosp.listDept.Add(new DEPT() { DeptId = 101 , DeptName ="外科" ,DoctorNum = 16});            hosp.listDept.Add(new DEPT() { DeptId = 201, DeptName = "眼科", DoctorNum = 5 });            hosp.listDept.Add(new DEPT() { DeptId = 202, DeptName = "肾内科", DoctorNum = 11 });            XmlDocument xmlDoc = new XmlDocument();//创建xml文档对象            XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);//创建xml声明            xmlDoc.AppendChild(xmlDec);//将xml声明添加到xml文档对象            XmlElement xmlRoot = xmlDoc.CreateElement("HOSPITAL");//创建 xml文档 根节点            xmlDoc.AppendChild(xmlRoot);            XmlElement xmlElem = xmlDoc.CreateElement("HOSPNAME");//创建医院名称节点            xmlElem.InnerText = hosp.HospName;//子节点文本内容            xmlRoot.AppendChild(xmlElem);//将医院名称节点加入到根节点中            XmlElement xmlElemDepts = xmlDoc.CreateElement("DEPTS");//创建科室节点            xmlRoot.AppendChild(xmlElemDepts);//将科室节点加入到根节点中                                            for (i = 0; i < hosp.listDept.Count; i++)            {                XmlElement xmlElemDeptChild = xmlDoc.CreateElement("DEPT");//创建子科室节点                XmlElement xmlElemDeptChildName = xmlDoc.CreateElement("DEPTNAME");//创建子科室名称节点                xmlElemDeptChildName.InnerText = hosp.listDept[i].DeptName;                xmlElemDeptChild.AppendChild(xmlElemDeptChildName);                XmlElement xmlElemDeptChildId = xmlDoc.CreateElement("DEPTID");//创建子科室ID节点                xmlElemDeptChildId.InnerText = hosp.listDept[i].DeptId.ToString();                xmlElemDeptChild.AppendChild(xmlElemDeptChildId);                xmlElemDepts.AppendChild(xmlElemDeptChild);                System.Console.WriteLine(hosp.listDept[i].DeptName);            }            xmlDoc.Save("gj.xml");            System.Console.ReadLine();        }    }    class HOSPITAL    {        public int HospId{get;set;}//医院编号        public string HospName{get;set;}//医院名字        public List<DEPT> listDept;//科室信息        public string Desc{get;set;}//医院描述信息    }    class DEPT    {        public int DeptId { get; set; }//科室id        public string DeptName { get; set; }//科室名字        public string Desc { get; set; }//描述信息        public int DoctorNum { get; set; }//医生人数    }}


0 0
原创粉丝点击