在实际项目中遇到一些关于xml操作的问题,被逼到无路可退的时候终于决定好好研究xml一番。xml是一种可扩展标记语言,可跨平台进行传输,因此xml被广泛的使用在很多地方。

本文由浅入深,首先就xml的基本操作增删改查进行简单介绍,接着对最近公司里面的一个项目中所涉及到xml的一些基本应用加以说明,最后介绍到xml不经常使用的命名空间问题,都是一些关于xml最基本的应用,本文在这里只是记录,以备以后查阅。

 

xml常用方法:

定义xml文档:XmlDocument xmlDoc = new XmlDocument();
初始化xml文档:xmlDoc.Load("D:\\book.xml");//找到xml文件
创建根元素:XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", "");
创建节点:XmlElement xeSub1 = xmlDoc.CreateElement("title");
查找Employees节点:XmlNode root = xmlDoc.SelectSingleNode("Employees");
添加节点:xe1.AppendChild(xeSub1);
更改节点的属性:xe.SetAttribute("Name", "李明明");
移除xe的ID属性:xe.RemoveAttribute("ID");
删除节点title:xe.RemoveChild(xe2);

 

1 创建xml文档

因为比较简单,直接写方法及结果。

public void CreateXMLDocument()
        {
            XmlDocument xmlDoc = new XmlDocument();           

//加入XML的声明段落,<?xml version="1.0" encoding="gb2312"?>
            XmlDeclaration xmlDeclar;
            xmlDeclar = xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);
            xmlDoc.AppendChild(xmlDeclar);           

//加入Employees根元素
            XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", "");
            xmlDoc.AppendChild(xmlElement);         

//添加节点
            XmlNode root = xmlDoc.SelectSingleNode("Employees");
            XmlElement xe1 = xmlDoc.CreateElement("Node");
            xe1.SetAttribute("Name", "李明");
            xe1.SetAttribute("ISB", "2-3631-4");         

//添加子节点
            XmlElement xeSub1 = xmlDoc.CreateElement("title");
            xeSub1.InnerText = "学习VS";
            xe1.AppendChild(xeSub1);

            XmlElement xeSub2 = xmlDoc.CreateElement("price");
            xe1.AppendChild(xeSub2);
            XmlElement xeSub3 = xmlDoc.CreateElement("weight");
            xeSub3.InnerText = "20";
            xeSub2.AppendChild(xeSub3);


            root.AppendChild(xe1);
            xmlDoc.Save("D:\\book.xml");//保存的路径
        }
View Code

相关文章: