Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and Duck-Typing XML in .NET?

I'm working with some XML representations of data instances. I'm deserializing the objects using .NET serialization but something in my soul is disturbed by having to write classes to represent the XML... Below is what I'd LOVE to do but I don't know if the syntax or if it is even possible:

Consider the following:

dim xmlObject = SomeXMLFunction() 'where some function returns an object/string representation of xml...

xmlObject.SomePropertyDefinedInTheXML = SomeFunction()

Any suggestions on approachs with this?

like image 660
Achilles Avatar asked Feb 12 '10 17:02

Achilles


2 Answers

Go and get xsd.exe. It'll create proper XML serialization classes from your schema definition. Automatically!

like image 185
David Schmitt Avatar answered Sep 17 '22 16:09

David Schmitt


VB.NET allows you to work with XML in a quite intuitive way:

Sub Serialize()
    Dim xml = <myData>
                  <someValue><%= someFunction() %></someValue>
              </myData>
    xml.Save("somefile.xml")
End Sub

Sub Serialize2()   ' if you get the XML skeleton as a string
    Dim xml = XDocument.Parse("<myData><someValue></someValue></myData>")
    xml.<myData>.<someValue>.Value = "test"
    xml.Save("somefile.xml")
End Sub

Sub Deserialize()
    Dim xml = XDocument.Load("somefile.xml")

    Dim value = xml.<myData>.<someValue>.Value
    ...
End Sub

Drawback: You don't have strong typing here; the Value property always returns a string.

like image 31
Heinzi Avatar answered Sep 19 '22 16:09

Heinzi