Search code examples
xmllinqsavexmldocument

Can't save Linq to XML elements addition


Having an issue opening, changing, and then saving changes to an XML file using Linq to XML.

Here's my code:

XDocument doc = XDocument.Load("xml/Campaigns.xml");

        XElement newCampaign = new XElement("campaign",
               new XAttribute("id", "2"),
               new XElement("name", "new campaign")
               );
        doc.Add(newCampaign);
        doc.Save("xml/Campaigns.xml");

I'm not getting any compile errors for opening, creating and adding the XElement, only when I try to save the changes.

The compile errors I'm seeing are: The best overloaded method match for 'System.Xml.Linq.XElement.Save(System.Xml.XmlWriter)' has some invalid arguments

and:

Argument 1: cannot convert from 'string' to 'System.Xml.XmlWriter'

I'm not sure why it's making or expecting me use a XmlWriter because according to this I can save a string in the Save Method:

http://msdn.microsoft.com/en-us/library/bb345830.aspx

If anyone could help, I'd be grateful.


Solution

  • My guess is you're using Silverlight (e.g. on Windows Phone 7) - where the Save method has fewer overloads. It's not clear where you're trying to save the document to, but if you are using Silverlight then you'll need to use one of the overloads listed in the linked page.