• ASP.NET


    对XML文件进行简单的增加,删除,修改,查看等功能。

    XML代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <books>
     <book>
      <name>哈里波特</name>
      <price>10</price>
      <memo>这是一本很好看的书。</memo>
     </book>
     <book id="B02">
      <name>三国演义</name>
      <price>10</price>
      <memo>四大名著之一。</memo>
     </book>
     <book id="B03">
      <name>水浒</name>
      <price>6</price>
      <memo>四大名著之一。</memo>
     </book>
     <book id="B04">
      <name>红楼</name>
      <price>5</price>
      <memo>四大名著之一。</memo>
     </book>
    </books>  

    C#代码:

    using System;
    using System.Xml;
    
    namespace XMLDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                XmlElement theBook = null, theElem = null, root = null;
                XmlDocument xmldoc = new XmlDocument();
                try
                {
                    xmldoc.Load(@"C:UsersHF_UltrastrongDesktopWFA_TestXMLDemoBooks.xml");
                    root = xmldoc.DocumentElement;
    
                    //---  新建一本书开始 ----
                    theBook = xmldoc.CreateElement("book");
                    theElem = xmldoc.CreateElement("name");
                    theElem.InnerText = "新书";
                    theBook.AppendChild(theElem);
    
                    theElem = xmldoc.CreateElement("price");
                    theElem.InnerText = "20";
                    theBook.AppendChild(theElem);
    
                    theElem = xmldoc.CreateElement("memo");
                    theElem.InnerText = "新书更好看。";
                    theBook.AppendChild(theElem);
                    root.AppendChild(theBook);
                    Console.Out.WriteLine("---  新建一本书开始 ----");
                    Console.Out.WriteLine(root.OuterXml);
                    //---  新建一本书完成 ----
    
                    //---  下面对《哈里波特》做一些修改。 ----
                    //---  查询找《哈里波特》----
                    theBook = (XmlElement)root.SelectSingleNode("/books/book[name='哈里波特']");
                    Console.Out.WriteLine("---  查找《哈里波特》 ----");
                    Console.Out.WriteLine(theBook.OuterXml);
                    //---  此时修改这本书的价格 -----
                    //getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,GetElementsByTagName("price")相当于SelectNodes(".//price")。
                    theBook.GetElementsByTagName("price").Item(0).InnerText = "15";
                    Console.Out.WriteLine("---  此时修改这本书的价格 ----");
                    Console.Out.WriteLine(theBook.OuterXml);
                    //---  另外还想加一个属性id,值为B01 ----
                    theBook.SetAttribute("id", "B01");
                    Console.Out.WriteLine("---  另外还想加一个属性id,值为B01 ----");
                    Console.Out.WriteLine(theBook.OuterXml);
                    //---  对《哈里波特》修改完成。 ----
    
                    //---  再将所有价格低于10的书删除  ----
                    theBook = (XmlElement)root.SelectSingleNode("/books/book[@id='B02']");
                    Console.Out.WriteLine("---  要用id属性删除《三国演义》这本书 ----");
                    Console.Out.WriteLine(theBook.OuterXml);
                    theBook.ParentNode.RemoveChild(theBook);
                    Console.Out.WriteLine("---  删除后的XML ----");
                    Console.Out.WriteLine(xmldoc.OuterXml);
    
                    //---  再将所有价格低于10的书删除  ----
                    XmlNodeList someBooks = root.SelectNodes("/books/book[price<10]");
                    Console.Out.WriteLine("---  再将所有价格低于10的书删除  ---");
                    Console.Out.WriteLine("---  符合条件的书有 " + someBooks.Count + "本。  ---");
    
                    for (int i = 0; i < someBooks.Count; i++)
                    {
                        someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
                    }
                    Console.Out.WriteLine("---  删除后的XML ----");
                    Console.Out.WriteLine(xmldoc.OuterXml);
    
                    xmldoc.Save("books.xml");//保存到books.xml
    
                    Console.In.Read();
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine(e.Message);
                }
    
                Console.ReadKey();
            }
        }
    }

    效果:

    //================================================================//

    XML:

    <?xml version="1.0" encoding="utf-8" ?> 
    <Computers>
      <Computer ID="11111111" Description="Made in China">
        <name>Lenovo</name>
        <price>5000</price>
      </Computer>
      <Computer ID="2222222" Description="Made in USA">
        <name>IBM</name>
        <price>10000</price>
      </Computer>
    </Computers>

    操作:

    using System;
    using System.Xml;
    
    namespace OperateXML
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    //xml文件存储路径
                    string myXMLFilePath = "E:\MyComputers.xml";
                    //生成xml文件
                    GenerateXMLFile(myXMLFilePath);
                    //遍历xml文件的信息
                    GetXMLInformation(myXMLFilePath);
                    //修改xml文件的信息
                    ModifyXmlInformation(myXMLFilePath);
                    //向xml文件添加节点信息
                    AddXmlInformation(myXMLFilePath);
                    //删除指定节点信息
                    DeleteXmlInformation(myXMLFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
    
            private static void GenerateXMLFile(string xmlFilePath)
            {
                try
                {
                    //初始化一个xml实例
                    XmlDocument myXmlDoc = new XmlDocument();
                    //创建xml的根节点
                    XmlElement rootElement = myXmlDoc.CreateElement("Computers");
                    //将根节点加入到xml文件中(AppendChild)
                    myXmlDoc.AppendChild(rootElement);
    
                    //初始化第一层的第一个子节点
                    XmlElement firstLevelElement1 = myXmlDoc.CreateElement("Computer");
                    //填充第一层的第一个子节点的属性值(SetAttribute)
                    firstLevelElement1.SetAttribute("ID", "11111111");
                    firstLevelElement1.SetAttribute("Description", "Made in China");
                    //将第一层的第一个子节点加入到根节点下
                    rootElement.AppendChild(firstLevelElement1);
                    //初始化第二层的第一个子节点
                    XmlElement secondLevelElement11 = myXmlDoc.CreateElement("name");
                    //填充第二层的第一个子节点的值(InnerText)
                    secondLevelElement11.InnerText = "Lenovo";
                    firstLevelElement1.AppendChild(secondLevelElement11);
                    XmlElement secondLevelElement12 = myXmlDoc.CreateElement("price");
                    secondLevelElement12.InnerText = "5000";
                    firstLevelElement1.AppendChild(secondLevelElement12);
    
    
                    XmlElement firstLevelElement2 = myXmlDoc.CreateElement("Computer");
                    firstLevelElement2.SetAttribute("ID", "2222222");
                    firstLevelElement2.SetAttribute("Description", "Made in USA");
                    rootElement.AppendChild(firstLevelElement2);
                    XmlElement secondLevelElement21 = myXmlDoc.CreateElement("name");
                    secondLevelElement21.InnerText = "IBM";
                    firstLevelElement2.AppendChild(secondLevelElement21);
                    XmlElement secondLevelElement22 = myXmlDoc.CreateElement("price");
                    secondLevelElement22.InnerText = "10000";
                    firstLevelElement2.AppendChild(secondLevelElement22);
    
                    //将xml文件保存到指定的路径下
                    myXmlDoc.Save(xmlFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
    
            private static void GetXMLInformation(string xmlFilePath)
            {
                try
                {
                    //初始化一个xml实例
                    XmlDocument myXmlDoc = new XmlDocument();
                    //加载xml文件(参数为xml文件的路径)
                    myXmlDoc.Load(xmlFilePath);
                    //获得第一个姓名匹配的节点(SelectSingleNode):此xml文件的根节点
                    XmlNode rootNode = myXmlDoc.SelectSingleNode("Computers");
                    //分别获得该节点的InnerXml和OuterXml信息
                    string innerXmlInfo = rootNode.InnerXml.ToString();
                    string outerXmlInfo = rootNode.OuterXml.ToString();
                    //获得该节点的子节点(即:该节点的第一层子节点)
                    XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
                    foreach (XmlNode node in firstLevelNodeList)
                    {
                        //获得该节点的属性集合
                        XmlAttributeCollection attributeCol = node.Attributes;
                        foreach (XmlAttribute attri in attributeCol)
                        {
                            //获取属性名称与属性值
                            string name = attri.Name;
                            string value = attri.Value;
                            Console.WriteLine("{0} = {1}", name, value);
                        }
    
                        //判断此节点是否还有子节点
                        if (node.HasChildNodes)
                        {
                            //获取该节点的第一个子节点
                            XmlNode secondLevelNode1 = node.FirstChild;
                            //获取该节点的名字
                            string name = secondLevelNode1.Name;
                            //获取该节点的值(即:InnerText)
                            string innerText = secondLevelNode1.InnerText;
                            Console.WriteLine("{0} = {1}", name, innerText);
    
                            //获取该节点的第二个子节点(用数组下标获取)
                            XmlNode secondLevelNode2 = node.ChildNodes[1];
                            name = secondLevelNode2.Name;
                            innerText = secondLevelNode2.InnerText;
                            Console.WriteLine("{0} = {1}", name, innerText);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
    
            private static void ModifyXmlInformation(string xmlFilePath)
            {
                try
                {
                    XmlDocument myXmlDoc = new XmlDocument();
                    myXmlDoc.Load(xmlFilePath);
                    XmlNode rootNode = myXmlDoc.FirstChild;
                    XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
                    foreach (XmlNode node in firstLevelNodeList)
                    {
                        //修改此节点的属性值
                        if (node.Attributes["Description"].Value.Equals("Made in USA"))
                        {
                            node.Attributes["Description"].Value = "Made in HongKong";
                        }
                    }
                    //要想使对xml文件所做的修改生效,必须执行以下Save方法
                    myXmlDoc.Save(xmlFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
    
            }
    
            private static void AddXmlInformation(string xmlFilePath)
            {
                try
                {
                    XmlDocument myXmlDoc = new XmlDocument();
                    myXmlDoc.Load(xmlFilePath);
                    //添加一个带有属性的节点信息
                    foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
                    {
                        XmlElement newElement = myXmlDoc.CreateElement("color");
                        newElement.InnerText = "black";
                        newElement.SetAttribute("IsMixed", "Yes");
                        node.AppendChild(newElement);
                    }
                    //保存更改
                    myXmlDoc.Save(xmlFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
    
            private static void DeleteXmlInformation(string xmlFilePath)
            {
                try
                {
                    XmlDocument myXmlDoc = new XmlDocument();
                    myXmlDoc.Load(xmlFilePath);
                    foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
                    {
                        //记录该节点下的最后一个子节点(简称:最后子节点)
                        XmlNode lastNode = node.LastChild;
                        //删除最后子节点下的左右子节点
                        lastNode.RemoveAll();
                        //删除最后子节点
                        node.RemoveChild(lastNode);
                    }
                    //保存对xml文件所做的修改
                    myXmlDoc.Save(xmlFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }

    操作总结:

           //所需要添加的命名空间
        using System.Xml;
        //初始化一个xml实例
        XmlDocument xml=new XmlDocument();
        //导入指定xml文件
        xml.Load(“xml文件路径path”);
        //指定一个节点
        XmlNode root=xml.SelectSingleNode("节点名称");
        //获取节点下所有直接子节点
        XmlNodeList childlist=root.ChildNodes;
        //判断该节点下是否有子节点
        root.HasChildNodes;
        //获取同名同级节点集合
        XmlNodeList nodelist=xml.SelectNodes("节点名称");
        //生成一个新节点
        XmlElement node=xml.CreateElement("节点名称");
        //将节点加到指定节点下,作为其子节点
        root.AppendChild(node);
        //将节点加到指定节点下某个子节点前
        root.InsertBefore(node,root.ChildeNodes[i]);
        //为指定节点的新建属性并赋值
        node.SetAttribute("id","11111");
        //为指定节点添加子节点
        root.AppendChild(node);
        //获取指定节点的指定属性值
        string id=node.Attributes["id"].Value;
        //获取指定节点中的文本
        string content=node.InnerText;
        //保存XML文件
        xml.Save(“xml文件存储的路径path”);

      

  • 相关阅读:
    libevent源码学习之event
    游戏寻路A*算法
    游戏地图动态生成
    一个基于protocol buffer的RPC实现
    TCMalloc源码学习(四)(小内存块释放)
    TCMalloc源码学习(三)(小块内存分配)
    TCMalloc源码学习(二)
    第五十四篇 Linux相关——远程连接SSH
    第五十三篇 Linux相关——Web服务器
    第五十二篇 Linux相关——数据库服务MySQL
  • 原文地址:https://www.cnblogs.com/KTblog/p/4896534.html
Copyright © 2020-2023  润新知