一 :效果显示
二 代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace CsharpConsoleApplication
{
class Program
{
static void Main(string[] args)
{
if (File.Exists("gj.xml"))//判断xml 文件是否存在
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("gj.xml");//存在的话则导入该xml文件
XmlElement xmlRoot = xmlDoc.DocumentElement;//获取xml 文件的根节点
XmlNodeList rootChilds = xmlRoot.ChildNodes;//获取根节点下的所有子节点
//遍历根节点下的所有子节点
foreach (XmlElement child in rootChilds)
{
System.Console.WriteLine(child.InnerText);
}
//遍历<DEPTS>节点下的所有子节点
foreach (XmlElement child in xmlRoot["DEPTS"])
{
System.Console.WriteLine(child.InnerText);
}
System.Console.ReadLine();
}
else
{
CreateXml();//不存在则创建文档
}
}
//创建xml文档
static void CreateXml()
{
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 = AddNodeToXml(xmlDoc, "HOSPITAL", ""); //创建根节点
XmlElement xmlElem = AddChildNode(xmlRoot, "HOSPNAME", hosp.HospName); //创建医院名称节点
XmlElement xmlElemDepts = AddChildNode(xmlRoot, "DEPTS", ""); //创建科室节点
for (i = 0; i < hosp.listDept.Count; i++)
{
XmlElement xmlElemDeptChild = AddChildNode(xmlElemDepts, "DEPTS", "");
AddChildNode(xmlElemDeptChild, "DEPTNAME", hosp.listDept[i].DeptName);
AddChildNode(xmlElemDeptChild, "DEPTID", hosp.listDept[i].DeptId.ToString());
System.Console.WriteLine(hosp.listDept[i].DeptName);
}
xmlDoc.Save("gj.xml");
//System.Console.ReadLine();
}
//向xml文档中添加节点
static XmlElement AddNodeToXml(XmlDocument xmlDoc, string elementName, string innerText)
{
XmlElement xmlElem = xmlDoc.CreateElement(elementName);
if (!string.IsNullOrEmpty(innerText))
{
xmlElem.InnerText = innerText;
}
xmlDoc.AppendChild(xmlElem);
return xmlElem;
}
//向xml中的指定节点中添加子节点
static XmlElement AddChildNode(XmlElement parentNode, string elementName, string innerText)
{
XmlElement childNode = parentNode.OwnerDocument.CreateElement(elementName);
if (!string.IsNullOrEmpty(innerText))
{
childNode.InnerText = innerText;
}
parentNode.AppendChild(childNode);
return childNode;
}
}
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; }//医生人数
}
}