I am searching for a method in F#
to construct an xml-tree
-structrue from a domain-class-model.
Guess you have some classes (types) with a parent-child-relationship like:
Container
-> Child
-> Child
-> Container
-> Child
-> Container
-> Child
-> Child
-> Container
-> etc.
The thing is that you cannot just simply translate this domain-tree
1:1 into XML, but you sometimes have to do slight modifications e.g.:
"If Type(Element) = A then add additionally XYZ-Element at root"
"If Type(Element) = B then nest B into ABC-Element"
Currently I am using XDocument
+ System.Xml.Linq
and some recursive function over my domain-class-model which get a reference to the first XElement
that has to be initialized from another function.
The whole "reference thing" seems fairly not functional and I many times whished to implement it in C# rather than F#.
Can someone suggest a more functional and natural-F#ish
way to solve such a task?
My Problem has been solved. For all who are interested in the code... I finally came up with sth. like this:
open System.Xml
open System.Xml.Linq
let xmlNs = "somenamespaceurl"
let XNameStd name = XName.Get(name, xmlNs)
let InsertIfCondition valueToInsert valueToCheck attributeName (element:XElement) =
if valueToInsert = valueToCheck then
element.Add(XAttribute(XNameStd attributeName,valueToInsert))
let InsertSthToTree(sth:DomainObject) (currentRoot:XElement) =
let element = XElement(XNameStd "MyDomainElementInXML")
currentRoot.Add(element)
InsertIfCondition(sth.BooleanProperty,true,"IsEnabled",element)
let CreateXMLDoc =
let someObj = DomainObject(...)
let doc = XDocument()
InsertSthToTree(doc.Root)
doc
If someone has a more functional-style of doing this I would appreciate any comments.