【C#】XML文件格式的写入

写入

			//在内存中构建一个Dom对象
            XmlDocument xmlDoc = new XmlDocument();

            //增加一个文档说明
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            xmlDoc.AppendChild(xmlDeclaration);

            //为文档添加一个根元素
            XmlElement rootElement = xmlDoc.CreateElement("school");
            xmlDoc.AppendChild(rootElement);

            //为根元素里面增加子元素,接下来增加元素都要讲子元素添加到rootElement元素下
            XmlElement xmlClassElement = xmlDoc.CreateElement("class");

            XmlAttribute attr = xmlDoc.CreateAttribute("id");
            attr.Value = "c01";

            //为class元素添加一个名字叫id的属性
            xmlClassElement.Attributes.Append(attr);

            rootElement.AppendChild(xmlClassElement);

            //将该Dom对象写入xml文件
            xmlDoc.Save("school.xml");

读取

			//将XML文件加载进来
            XDocument document = XDocument.Load(@"D:\桌面\CS拓展\ConsoleApplication1\XML的读写\bin\Debug\school.xml");

            //获取到XML的根元素进行操作
            XElement root = document.Root;
            XElement ele = root.Element("school");

            //获取name标签的值
            //XElement shuxing = ele.Element("class");
            //Console.WriteLine(shuxing.Value);

            //获取根元素下的所有子元素
            IEnumerable<XElement> enumerable = root.Elements();
            textBox1.Text = enumerable.ToString();
            foreach (XElement item in enumerable)
            {
                foreach (XElement item1 in item.Elements())
                {
                    textBox1.Text = item1.Name.ToString();
                }
                textBox1.Text = item.Attribute("id").Value;
            }

猜你喜欢

转载自blog.csdn.net/ywq1016243402/article/details/85411907