Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

XML Serialization of non-public classes

Hello all,

I am looking for a way to output the Public Properties of our classes to XML - just like the XmlSerializer does. However, trying to run it on a class with a Friend, Protected, etc modifier results in the following error:

System.InvalidOperationException: AssemblyName.BusinessObject is inaccessible due to its protection level. Only public types can be processed.

The code I'm using is:

Dim bizObj As New BusinessObject

Dim xs As New System.Xml.Serialization.XmlSerializer(GetType(BusinessObject))

Dim fs As New System.IO.FileStream("test.xml", IO.FileMode.Create)

xs.Serialize(fs, bizObj)

fs.Close()

I've looked around on Google and several Message Boards but can't seem to find any answers. Can you use XML serialization on a non-public class?

CF
Monday, May 03, 2004

I think the answers to your questions are in this book:

http://www.lhotka.net/ArticleIndex.aspx?area=CSLA%20.NET

From memory, the XML Serializer won't work, but you could always use Reflection to do the work (if you don't care about performance too much).

The book has been mentioned here before (actually over at JoS I think) and is an interesting read.

Steve Jones (UK)
Tuesday, May 04, 2004

Thanks. I ended up writing my own. This isn't the final I used, but here is a piece of it I placed in one of our supertypes if anyone was interested:

Public Function ToXml() As System.Xml.XmlDocument

Dim props As System.Reflection.PropertyInfo()
        Dim prop As PropertyInfo
        Dim doc As New System.Xml.XmlDocument
        Dim root As System.Xml.XmlNode = doc.AppendChild(doc.CreateElement(Me.GetType.Name))

        props = Me.GetType.GetProperties(BindingFlags.Instance _
                    Or BindingFlags.Public Or BindingFlags.NonPublic _
                    Or BindingFlags.DeclaredOnly Or BindingFlags.GetProperty)

    For Each prop In props
                Dim mpNode As System.Xml.XmlNode
                mpNode = root.AppendChild(doc.CreateElement(prop.Name))
                Try
                    mpNode.InnerText = prop.GetValue(Me, Nothing).ToString()
                Catch ex As Exception
                    Debug.WriteLine("***Append: " + ex.ToString() + "***")
                    mpNode.InnerText = String.Empty
                End Try
            Next

Return doc

End Function

CF
Tuesday, May 04, 2004

*  Recent Topics

*  Fog Creek Home