Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,

I am working on xml.

successfully save my xml document when I update this not working.
my code is

if (!File.Exists(path))
            {
                //save
                XElement xml = new XElement("Formulas",
                                new XElement("Formula", txtFormula.Text));
                xml.Save(path);
            }
            else
            {
                //update
                XDocument doc = XDocument.Load(path);
                var xmlupdate = doc.Descendants().Elements("Formulas").Where(f => f.Element("Formula").Value == txtFormula.Text).FirstOrDefault();
                doc.Save(path);


            }


where I went wrong.
Posted
Comments
Sergey Alexandrovich Kryukov 3-Apr-13 1:19am    
"Not working" is not informative.
—SA
U@007 3-Apr-13 1:40am    
when update return null value.So, how to update this

Hi,

You performed update in conditional statement.

Try below code
C#
if (!File.Exists(path))
            {
                //save
                XElement xml = new XElement("Formulas",
                                new XElement("Formula", txtFormula.Text));
                xml.Save(path);
            }
            else
            {
                //update
                XDocument doc = XDocument.Load(path);
                var xmlupdate = doc.Descendants("Formulas")
                    .FirstOrDefault().Element("Formula").Value = txtFormula.Text;
                doc.Save(path);
            }
 
Share this answer
 
Comments
U@007 3-Apr-13 1:38am    
it's not working patel
vijay__p 3-Apr-13 1:43am    
Dear i have tested this code in sample application and it worked!
Just use one codition for .FirstOrDefault();
if it is null then do not perform any operation as no element exists.


Try below code. it is from sample application

var path = @"C:\Temp\test.xml";
if (!File.Exists(path))
{
//save
XElement xml = new XElement("Formulas",
new XElement("Formula", DateTime.Now.ToString()));
xml.Save(path);
}
else
{
//update
XDocument doc = XDocument.Load(path);
var xmlupdate = doc.Descendants("Formulas")
.FirstOrDefault().Element("Formula").Value = "formula_" + DateTime.Now.ToString();
doc.Save(path);
}
U@007 3-Apr-13 1:59am    
ya it's working fine. actually I written the dobule equals insted of single equals. now fine.
Thank you

:) 5+.
Sorry I don't speak C but I think you may be having an issue with using the XDocument. It is far easier to work with XElement until you get some practice with XDocument. Try [this] for starters. See the section on using XElement without using XDocument.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900