创建XML文件以及XML中的节点和更新Xml文件中的节点的值

来源:互联网 发布:福建软件职业技术学校 编辑:程序博客网 时间:2024/06/02 04:15

         最近在项目中用到了XML文件,需要将一些配置信息保存到指定的XML文件中。因此就用到了对XML文件中节点的值的更新的功能。

首先我们来创建一个XML文件,并在文件中创建几个值,我们来看下Demo的代码:

private CreateXmlFile()

{

    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();

   doc.LoadXml("<Category><name>Kevin</name></Category>");

    // Add a price element.
    XmlElement newElem = doc.CreateElement("MobilePhone");
    newElem.InnerText = "NOKIA";
    doc.DocumentElement.AppendChild(newElem);


    // Save the document to a file. White space is
    // preserved (no white space).
    doc.PreserveWhitespace = true;
    doc.Save("data.xml");

}

 

 

下面提供一个对XML文件中节点值更新的方法,代码如下:

 

private void UpdateXMLNodeValue()

{

       string strXmlPath = Application.StartupPath + "\\data.xml";
   
        doc.Load(strXmlPath);
        xe = doc.FirstChild as XmlElement;
        XmlNode xnRC = xe.SelectSingleNode("MobilePhone");
        if (xnRC != null)
          {
             xnRC.InnerText = "Apple";
             doc.Save(strXmlPath);

          }

}