Search code examples
.netasp.netvb.netgenericsduck-typing

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?


Solution

  • 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.