xml 以键值对形式存储

1.XM 文件:

<?xmlversion="1.0"encoding="utf-8"?>

<Root>

  <Templete alias="">

    <TempleteName>atest20120806test</TempleteName>    

   <Templetevalue>cb1,cb7,cb9,cb5,cb2,SRRcb7,PVRcb2,PVRcb6,PVRcb10</Templetevalue>

 </Templete>

<Templete alias="">

    <TempleteName>templateaaaa</TempleteName>

   <Templetevalue>cb1,cb7</Templetevalue>

</Root>

2.存储便利xml:

public staticbool CreateXML(string TempleteName, string TempleteValue, string UserName, string xpath)

        {

try

            {

               XmlDocument xmlDoc = newXmlDocument();

                xmlDoc.Load(xpath);

               XmlNode root = xmlDoc.SelectSingleNode("Root");//查找

               if (root == null)

                   returnfalse;

               bool isExistsNode = false;

               //遍历xpath节点下的所有子节点

               foreach (XmlNode node in root.ChildNodes)

                {

                   string curTempleteName = node.ChildNodes[0].InnerText;

                   string curTempleteValue = node.ChildNodes[1].InnerText;

                   if (curTempleteName == TempleteName)

                    {

                       //存在此节点则更新

                        node.ChildNodes[1].InnerText = TempleteValue;

                       XmlNode nodes = node.ChildNodes[1].ParentNode;//找到此节点的父节点

                       XmlElement partentXE = (XmlElement)nodes;//将父节点类型转换为XmlElement

                        partentXE.SetAttribute("alias", UserName);

                        isExistsNode =true;

                       break;

                    }

                }

               if (!isExistsNode)//不存在重复,创建

                {

                    XmlElement xe1 = xmlDoc.CreateElement("Templete");//创建一个节点

                    xe1.SetAttribute("alias", UserName);

                   XmlElement xe2 = xmlDoc.CreateElement("TempleteName");

                    xe2.InnerText = TempleteName;//设置文本节点

                    xe1.AppendChild(xe2);//添加到节点中

                   XmlElement xe3 = xmlDoc.CreateElement("Templetevalue");

                    xe3.InnerText = TempleteValue;//设置文本节点

                    xe1.AppendChild(xe3);//添加到节点中

                    root.AppendChild(xe1);//添加到节点中

                }

                xmlDoc.Save(xpath);

               return true;

            }

           catch (Exception ex)

            {

               return false;

            }

        }

你可能感兴趣的:(xml)