用Linq,XDocument和XElement可以实现,不过有些麻烦,简单一句代码的方法我也不知道

解决方案 »

  1.   

    XmlDocument xmlDoc = new XmlDocument();
    try
    {
       xmlDoc.Load(xmlFileName); //加载XML文档
       XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath); //xpath节点
       //Get the root node
       XmlNode RootElem = xmlDoc.DocumentElement;
       //Get lastest update record
       XmlNode TempElem = RootElem.LastChild;
       string id = TempElem.Attributes["id"].Value;
       int userId = Int32.Parse(id) + 1;
       if (xmlNode != null)
       {
          XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
          //如果属性和值参数都不为空则在此新节点上新增属性
          if (!string.IsNullOrEmpty(pwd) && !string.IsNullOrEmpty(name))
          {
             XmlAttribute xmlAttribute = xmlDoc.CreateAttribute("name");
             xmlAttribute.Value = name;
             XmlAttribute xmlAttribute1 = xmlDoc.CreateAttribute("pwd");
             xmlAttribute1.Value = pwd;
             XmlAttribute xmlAttribute2 = xmlDoc.CreateAttribute("id");
             xmlAttribute3.Value = userId.ToString();
             subElement.Attributes.Append(xmlAttribute);
             subElement.Attributes.Append(xmlAttribute1);
             subElement.Attributes.Append(xmlAttribute2);
          }      xmlNode.AppendChild(subElement);
        }
        xmlDoc.Save(xmlFileName); //保存到XML文档
    }