Ajay
Ajay

Reputation: 6590

Issue in XDocument.Save Method

I am trying to insert data in existing XMl file. I have the following code.

        string file = MapPath("~/XMLFile1.xml");
        XDocument doc;
        //Verify whether a file is exists or not
        if (!System.IO.File.Exists(file))
        {
            doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                new System.Xml.Linq.XElement("Contacts"));
        }
        else
        {
            doc = XDocument.Load(file);
        }
        foreach (var c in MyContactsLst)
        {
            //var contactsElement = new XElement("Contacts",
            var contactsElement = new XElement("Contact",
                                  new XElement("Name", c.FirstOrDefault().DisplayName),
                                  new XElement("PhoneNumber", c.FirstOrDefault().PhoneNumber.ToString()),
                                  new XElement("Email", "[email protected]"));
            doc.Root.Add(contactsElement);
            doc.Save(file);
        }

The first issue is in first line of code i.e. MapPath("~/XMLFile1.xml"); It gives me an error

The name 'MapPath' does not exist in the current context

The second issue is in doc.Save(file); It gives me an error

The best overloaded method match for 'System.Xml.Linq.XDocument.Save(System.IO.Stream)' has some invalid arguments

I have refer this question How to insert data into an existing xml file in asp.net?

I am learning XML. So, how can I solve this?

Upvotes: 2

Views: 3264

Answers (2)

susieloo_
susieloo_

Reputation: 1519

Adding onto Kajzer's answer, here is another alternative that may be easier to grasp and use for saving an XDocument:

string path = "[some path]";

using (Stream stream = File.Create(path))
{
    doc.Save(stream);
}

There is just one using statement, and you'll only need the System.IO class as it provides both the Stream and File classes for you to use - making this the most straightforward and easiest to understand solution.

Upvotes: 0

Kajzer
Kajzer

Reputation: 2385

The reason why MapPath does not exist in the current context is because it is a method of HttpServerUtility class, and as far as I know, it is not supported on Windows Phone.

Try loading the XDocument like this:

XDocument xdocument = XDocument.Load("XMLFile1.xml");

EDIT: You were having an error saving the document. Here is an answer from a related thread:

using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
     using (Stream stream = storage.CreateFile("data.xml"))
     {
         doc.Save(stream);
     }
}

Upvotes: 3

Related Questions