XML File Handling Using C#

hi

how can i check whether the XML file is exist or not.

in case of existing how can i go to particular Node and Update it.

i am finding tons of sample code for reading and writing XML files.

but i have to check whether the file exist or not.

pls help me out.

Thanks and regards

ranu.



Answer this question

XML File Handling Using C#

  • kuankuo123

    To check if the file exists you can use the System.IO.File.Exists method, that will tell you if a file exists. Then to update a particular node then one way is to load the data into an XmlDocument and use the SelectSingleNode method to retrieve the node you want, this uses an XPath query to obtain the node.

    Mark.



  • Dan-Teklynx

    This should do it for you :

    string path = "Accounts/" + ID + ".xml";

    // Check if the File Exists

    if (File.Exists(path))

    {

    // We are good, to proceed

    XmlDocument xmlDoc = new XmlDocument();

    xmlDoc.Load(path);

    XmlNodeList nList = xmlDoc.SelectNodes("Accounts/AccountInfo");

    foreach (XmlNode xNode in nList)

    {

    double begbal = Convert.ToDouble(xNode["BegBal"].InnerText);

    double bal = Convert.ToDouble(xNode["NewBal"].InnerText);

    }

    xNode["Name"].InnerText = Name;

    xNode["Type"].InnerText = Type;

    xNode["Bank"].InnerText = Bank;

    xNode["Account"].InnerText = Acct;

    xNode["BegBal"].InnerText = bbal.ToString();

    xNode["NewBal"].InnerText = newbal.ToString();

    xNode["Currency"].InnerText = Currency;

    xmlDoc.Save(path);

    break;

    }

    }

    else

    {

    // File Not found...We don't need to Create it

    }

    The above example tries to open for the file, if available and then get something out of the XML file and then update the file using the nodes..

    XML File Looks Like this

    <something>

    <account>123</account>

    <type>some</type>

    </something>

    Hope this helps.

    Thanks,

    Harsimrat


  • olakara

    Thanks friends

    its working now.


  • XML File Handling Using C#