Search code examples
f#type-providers

How do I edit an XML file using type providers?


I understand how to retrieve data from an XML source using type providers. However, I need to then modify a particular part of the XML and save it to disk. I have tried assigning a value to the node using <- but the property is read-only.

For example:

let doc = MyXml.load fileName
doc.ItemId.Id <- "newId" // doesn't work
doc |> saveXml

There is a similar question for JSON where the suggestion is to create a new object, but this is specifically for XML.


Solution

  • While researching my question I found that you can use the .XElement accessor to get a reference to a mutable XElement object. Thus a solution is:

    let doc = MyXml.load fileName
    doc.ItemId.XElement.Element(XName.Get "Id").Value <- "newId" // tada
    doc.XDocument.Save(...)
    

    Note that you have to use the .XElement accessor on the parent if you're modifying a leaf node. This is because the leaf node's type is a primitive and doesn't have an .XElement accessor of its own. A slight shame, but I suppose it makes life easier on the other side when you want read-only access to the value.