Solved

Contents of ArrayList to XML.

Posted on 2009-05-16
8
374 Views
Last Modified: 2012-05-07
All,

I'm not sure if I'm just not completely understanding or am missing something but I have an Arraylist that was generated fro reading an XML.

Now, at the end of the processing which may have had items added to it and write it back to the XML then close the XML file and I'm done.

Do I have to serialize the ArrayList? Then load it into an XMLDocument and save?

If I have to serialize the ArrayList does anybody have any examples or reference to an example for serializing?

Any assistance would be greatly appreciated.
0
Comment
Question by:davism
  • 4
  • 4
8 Comments
 
LVL 4

Expert Comment

by:TMarkham1
ID: 24404365
Can you share how your ArrayList is setup, or how the XML is formatted? I'm assuming you need / want the XML generated from the ArrayList to follow the same schema as the XML used to create the ArrayList. Is this correct? I should be able to throw something together for you once I have a full understanding of the requirements.
0
 
LVL 1

Author Comment

by:davism
ID: 24404432
Arraylist is something like comprised of structure items.

So my structure is called object list.

Let's say it's called objList

Name
City
State

So I have something to the effect of:

objList.Name = "MyName"
objList.City = "MyCity"
objList.State = "MyState"

My arraylist let's call aList.

After I do the objList stuff I then do:

aList.Add(objList)

I repeat that process reading through the XML file.

The XML file based the the above looks like:

<Event Name>
     <City/>
     <State/>
</Event
Or with data:

<Event Name="MyName"
        <City>"MyCity"</City>
        <State>"MyState"</State>
</Event>

Now, after the arraylist is loaded from the XML, I want add another event:

objList.Name="MyName2"
objList.Name="MyCity2"
objList.Name="MyState2"
aList.Add(objList)

When I'm done with everything in the app I want to take the arraylist and put it to an XML so the XML would look like:

<Event Name="MyName"
        <City>"MyCity"</City>
        <State>"MyState"</State>
</Event>
<Event Name="MyName2"
        <City>"MyCity2"</City>
        <State>"MyState2"</State>
</Event>

Hope this makes better sense.

I've been playing around with a dataset but I'm not sure if that is the best approach either so I'd be interested in what you throw together.

Thanks!
0
 
LVL 4

Expert Comment

by:TMarkham1
ID: 24404845
See below for an example on how I've handled this in the past. If you're using .NET 2.0 or greater, you have Generic Lists you can take advantage of, which I used in my example below... but if you're sticking with an ArrayList the concept is pretty much the same. I've included an Interface which I found handy when dealing with multiple objects requiring XML persistence.

Just create a new Windows Application, drag two buttons onto Form1, and then paste in the following code.

Let me know what you think.
Imports System.Xml

Imports System.Text
 

Public Class Form1

    Dim EventItemList As New List(Of EventItem)
 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Loads a List of Event items from XML
 

        Dim sbXML As New StringBuilder

        With sbXML

            .Append("<Events>")

            .Append("<Event Name='MyName1'><City>MyCity1</City><State>MyState1</State></Event>")

            .Append("<Event Name='MyName2'><City>MyCity2</City><State>MyState2</State></Event>")

            .Append("<Event Name='MyName3'><City>MyCity3</City><State>MyState3</State></Event>")

            .Append("<Event Name='MyName4'><City>MyCity4</City><State>MyState4</State></Event>")

            .Append("</Events>")

        End With

        Dim xmldoc As New XmlDocument

        xmldoc.LoadXml(sbXML.ToString)
 

        For Each eventnode As XmlNode In xmldoc.SelectNodes("/Events/Event")

            Dim newEvent As New EventItem

            newEvent.FromXML(eventnode)

            EventItemList.Add(newEvent)

        Next
 

        'Do what you want with the list of EventItems
 

    End Sub
 

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        'Writes a list of Event item objects to XML.
 

        Dim xmldoc As New XmlDocument

        Dim eventsnode As XmlElement

        Try

            eventsnode = xmldoc.CreateElement("Events")

            For Each eitem As EventItem In Me.EventItemList

                eitem.ToXML(eventsnode)

            Next

            xmldoc.AppendChild(eventsnode)
 

            'Do what you want with the xmldoc object

        Catch ex As Exception
 

        End Try

    End Sub

End Class
 
 

Public Class EventItem

    Implements IPersistXML
 

#Region "Private Member Variables"

    Private _Name As String

    Private _City As String

    Private _State As String

#End Region
 

#Region "Public Properties"

    Public Property Name() As String

        Get

            Return _Name

        End Get

        Set(ByVal value As String)

            _Name = value

        End Set

    End Property
 

    Public Property City() As String

        Get

            Return _City

        End Get

        Set(ByVal value As String)

            _City = value

        End Set

    End Property
 

    Public Property State() As String

        Get

            Return _State

        End Get

        Set(ByVal value As String)

            _State = value

        End Set

    End Property

#End Region
 

    Public Sub FromXML(ByVal SourceNode As System.Xml.XmlNode) Implements IPersistXML.FromXML

        Dim cityNodes As XmlNodeList

        Dim stateNodes As XmlNodeList
 

        Try

            Me._Name = SourceNode.Attributes("Name").Value

            cityNodes = SourceNode.SelectNodes("City")

            stateNodes = SourceNode.SelectNodes("State")

            If cityNodes.Count > 0 Then

                For Each citynode As XmlNode In cityNodes

                    Me._City = citynode.InnerText

                Next

            End If

            If stateNodes.Count > 0 Then

                For Each statenode As XmlNode In stateNodes

                    Me._State = statenode.InnerText

                Next

            End If

        Catch ex As Exception

            MessageBox.Show(ex.Message)
 

        End Try

    End Sub
 

    Public Sub ToXML(ByVal TargetNode As System.Xml.XmlNode) Implements IPersistXML.ToXML

        Dim newEventNode As XmlNode

        Dim newCityNode As XmlNode

        Dim newStateNode As XmlNode

        Dim NameAttrib As XmlAttribute

        Try

            newEventNode = TargetNode.OwnerDocument.CreateElement("Event")

            NameAttrib = newEventNode.OwnerDocument.CreateAttribute("Name")

            newEventNode.Attributes.Append(NameAttrib)

            newEventNode.Attributes("Name").Value = Me._Name

            newCityNode = TargetNode.OwnerDocument.CreateElement("City")

            newStateNode = TargetNode.OwnerDocument.CreateElement("State")

            newCityNode.InnerText = Me._City

            newStateNode.InnerText = Me._State

            newEventNode.AppendChild(newCityNode)

            newEventNode.AppendChild(newStateNode)

            TargetNode.AppendChild(newEventNode)

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

    End Sub

End Class
 

Public Interface IPersistXML

    Sub FromXML(ByVal SourceNode As Xml.XmlNode)

    Sub ToXML(ByVal TargetNode As Xml.XmlNode)

End Interface

Open in new window

0
 
LVL 1

Author Comment

by:davism
ID: 24408230
I haven't tried this yet but out of curiousity, why would I need an interface on this rather than serialization?

Please let me know.

Thanks
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 4

Expert Comment

by:TMarkham1
ID: 24408892
You don't need the interface. It's just nice to have if you are going to have many objects that you want to implement the same functionality on.

You could just implement two methods, one to create you ArrayList from XML, and one to save your ArrayList to XML... and be done with it.

Or, you could try this route:

http://msdn.microsoft.com/en-us/library/ms950721.aspx

Lots of way to skin a cat.
0
 
LVL 1

Author Comment

by:davism
ID: 24408939
Interesting...

You mentioned: "You could just implement two methods, one to create you ArrayList from XML, and one to save your ArrayList to XML... and be done with it."

That second one "...and one to save your Arraylist to XML..." Should I iterate through the XML and only append on nodes that aren't found? So basically I already have the XML:

<Event Name="MyName"
        <City>"MyCity"</City>
        <State>"MyState"</State>
</Event>

and then have new item MyName2 in the arraylist I add another node of Event? I know it would be "new" because I would iterate through the existing XML and comparing to the ArrayList item and if not found then I would know to add the arraylist item?

Is that a good approach? Serialization or not...is that a good approach? If so, would I even need serialization then?


0
 
LVL 4

Accepted Solution

by:
TMarkham1 earned 125 total points
ID: 24412093
I'm probably not fully understanding what you're trying to accomplish.

But, let me give you an idea on how I've implemented this in the past. Were I work, we have an Employee Context object that is comprised of various things (Credentials, Preferences, etc). Whenever an employee logs in to our system, we create a context object for the employee. To do this, we check the database for an employee record. We then check to see if the user has a valid context (saved as XML in one of the columns of the employee record). If so, we create an Employee Context object based off of the employee's context XML from the database using the same method I decribed in an earlier post (FromXML). At this point, the employee goes about his / her work... and when they logout, we then use the ToXML method on the Employee Context object to persist the object back to XML, and finally we save that new XML back to the database. The entire XML document gets recreated upon save. We don't iterate through the XML DOM at all checking to see if certain elements or attributes exist and append missing items. The Employee Context object has all it needs to persist itself back into a fully valid XML document.

Does that help?

You certainly could do what you are suggesting, but in my opinion unless you have a specific need to do it that way, it might just add unnecessary overhead to the process.

Finally, in my approch above, I don't have my object marked as Serializable or use Serialization in the way you are thinking. I am serializing the object on my own to XML, using my own specifications. It may seem like a little more work, but that work is all upfront. Once your have the FromXML and ToXML methods coded for the object you want serialize to and from XML, it just works from then on.
0
 
LVL 1

Author Closing Comment

by:davism
ID: 31582285
Thanks for the information! I will come in handy.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now