XML

  • 可扩展的标记语言(eXtensible Markup Language)
  • 什么是XML,学它有什么用。优点:容易读懂;格式标准任何语言都内置了XML分析引擎,不用单独进行文件分析引擎的编写。
  • 用普通二进制传输数据的缺点,解析方式各异。“88888|99999”
  • XML语法规范:标签(Tag)、嵌套(Nest)、属性。标签要闭合,属性值要用""包围,标签可以互相嵌套
  • 大小写敏感(CaseSensitive)
  • XML树,父节点、子节点、兄弟节点(siblings)
  • XML和HTML的区别:XML中元素必须关闭!XML中元素的属性值必须用引号。
创建Xml文件
            // 创建Xml文件
            XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0","utf-8" , null);
            //创建父节点
            XmlElement parentNode = xmlDoc.CreateElement("Parent");
            xmlDoc.AppendChild(parentNode);

            //创建带内容的子节点
            XmlElement childNode = xmlDoc.CreateElement("Child");
            childNode.InnerText = "我是子节点";
            parentNode.AppendChild(childNode);

            //创建带属性的子节点
            XmlElement childNodeWithAttribute = xmlDoc.CreateElement("ChildWithAttribute");
            childNodeWithAttribute.SetAttribute("name", "value");
            parentNode.AppendChild(childNodeWithAttribute);

            //保存Xml文件
            xmlDoc.Save(@"C:\Users\Administrator\Desktop\123456789.xml");
            Console.WriteLine("保存成功");
获取Xml文档里的内容
            XmlDocument doc = new XmlDocument();
            doc.Load( @"C:\1.xml");

            //获取跟节点
            // XmlNode parentNode = doc.SelectSingleNode("Parent");
            XmlElement parentNode = doc.DocumentElement;
           
            XmlNodeList xnl = parentNode.ChildNodes;
            foreach (XmlNode node in xnl)
            {
                Console.WriteLine(node.ChildNodes[0].InnerText);
            }
获取Xml属性
            XmlDocument doc = new XmlDocument();
            doc.Load(@"C:\Users\Administrator\Desktop\123456789.xml");

            //第一种方式
            XmlElement parent = doc.DocumentElement;
            XmlNode items = parent.SelectSingleNode("ChildWithAttribute");
            Console.WriteLine(items.Attributes["name"].Value);

            //第二种使用xpaths的方式去读,直接定位
            XmlNodeList xnl= doc.SelectNodes("Parent/ChildWithAttribute");
            foreach (XmlNode item in xnl)
            {
                Console.WriteLine(items.Attributes["name"].Value);
            }
            //第三种方式
            XmlNode node = doc.SelectSingleNode("Parent/ChildWithAttribute[@name=\"value\"]");
            Console.WriteLine(node.Attributes[0].Value);

            Console.Read();
原文地址:https://www.cnblogs.com/hejinyang/p/2810666.html