代码改变世界

C#用XmlDocument操作XML

2012-11-30 14:52  sql_manage  阅读(417)  评论(0编辑  收藏  举报

1.加载xml文件

   string xmlPath = AppDomain.CurrentDomain.BaseDirectory+"xml/test.xml";
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.Load(xmlPath);//这里是xml文件的路径

   string xmlString="<books><book>test</book></books>";

   xmlDoc.LoadXml(xmlString);//这里是加载一段XML字符串并将它转换为xml

2、用xpath来查询节点

    XmlNodeList nodeList = xmlDoc.SelectNodes("/bookstore/book/title");//查询节点集

    XmlNodeList node = xmlDoc.SelectSingleNode("/bookstore/book/title[@speciality='computer']");//根据属性查询单个节点

3、遍历节点集

    foreach (XmlNode node in nodeList)
4、给某个节点添加新的属性

    XmlAttribute attr = xmlDoc.CreateAttribute("specialty");

    attr.Value = "computer";
    node.Attributes.Append(attr);

5、删除某个节点的某个属性,当然也可以根据属性的下标来删除(这里就不举例了)

     XmlNode node = xmlDoc.SelectSingleNode("/bookstore/book[@ISBN='1-861003-11-0']/title");
            XmlAttribute attr = node.Attributes["specialty"];
            if (attr.Value == "computer1")
            {
                node.Attributes.Remove(attr);
            }

6、修改某个节点的value值,但节点的tag名称是不能修改的,只能先删除再添加

      node.Attributes["specialty"].Value="xiaochun";

7、添加节点

    XmlElement element = xmlDoc.CreateElement("book");
            element.InnerXml = "<test>create element</test>";
            XmlNode node = xmlDoc.SelectSingleNode("/bookstore");
            node.AppendChild(element);

8、修改节点就是先查询到某个节点,然后再将他的属性再设置一次就行了(这里就不举例了)

9、删除节点
     XmlNodeList nodeList = xmlDoc.SelectNodes("/bookstore/book");
            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes.Count == 0)//这里表示没有属性的节点
                {
                    xmlDoc.SelectSingleNode("/bookstore").RemoveChild(node);
                }
            }

10、保存xml文档

     xmlDoc.Save(xmlPath);

11、创建一个完整的XML文档

      XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration declare = xmlDoc.CreateXmlDeclaration("1.0","gb2312",null);
            xmlDoc.AppendChild(declare);

            XmlElement root = xmlDoc.CreateElement("books");
            xmlDoc.AppendChild(root);

            XmlElement bookElement = xmlDoc.CreateElement("book");
            bookElement.InnerXml = "<name>javascript</name>";
            xmlDoc.SelectSingleNode("/books").AppendChild(bookElement);

            XmlElement bookElement2 = xmlDoc.CreateElement("book");
            bookElement.InnerXml = "<name>xml</name>";
            XmlAttribute attr = xmlDoc.CreateAttribute("title");
            attr.Value = "test";
            bookElement2.Attributes.Append(attr);
            xmlDoc.SelectSingleNode("/books").AppendChild(bookElement2);

            xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory+"/xml/test2.xml");