当前位置:编程学习 > XML/UML >>

生成xml与获取xml

  private string fileName = "adphoto.xml";

 

  /// <summary>
        /// 插入XML
        /// </summary>
        /// <param name="id"></param>
        /// <param name="imageName"></param>
        /// <param name="fileName"></param>
        public void AddImg(string id, string imageName, string fileName)
        {
            fileName = "~/xml/" + fileName;
            var sPath = Server.MapPath(fileName);
            XmlDocument doc = new XmlDocument();
            doc.Load(sPath);
            XmlNode root = doc.SelectSingleNode("resultxml");//查找<resultxml>
            XmlElement xe1 = doc.CreateElement("item");
            xe1.SetAttribute("id", id);
            xe1.SetAttribute("thumb", imageName);


            root.AppendChild(xe1);
            doc.Save(sPath);
        }

 

 

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="upimgName"></param>
        /// <param name="fileName"></param>
        public void UpdateImg(string keyName, string upimgName, string fileName)
        {
            fileName = "~/xml/" + fileName;
            var sPath = Server.MapPath(fileName);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(sPath);
            XmlNodeList elemList = xmlDoc.GetElementsByTagName("item");
            foreach (XmlNode list in elemList)
            {
                XmlElement element = list as XmlElement;
                string str = element.GetAttribute("thumb");
                if (str == keyName)
                {
                    element.SetAttribute("thumb", upimgName);
                    element.SetAttribute("id", keyName);
                }
            }
            XmlTextWriter xw = new XmlTextWriter(new StreamWriter(sPath));
            xw.Formatting = Formatting.Indented;
            xmlDoc.WriteTo(xw);
            xw.Close();

        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="fileName"></param>
        public void DelImg(string keyName, string fileName)
        {


            // fileName = "photo_list.xml";
            // keyName = "9a.jpg";
            fileName = "~/xml/" + fileName;
            var sPath = Server.MapPath(fileName);
            XmlDocument doc = new XmlDocument();
            doc.Load(sPath);


            XmlNodeList xnl = doc.SelectSingleNode("resultxml").ChildNodes;


            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("thumb") == keyName)
                {


                    doc.SelectSingleNode("resultxml").RemoveChild(xe);
                }
            }
            doc.Save(sPath);


        }

 作者:zhangqihua0

补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,