Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate XML with multiple objects

Tags:

c#

xml

I have multiple classes of objects and am attempting to convert them to one xml document.

The first class is:

public class GameObject
{
// data members
public int squareID;
public int objectID;
public String objectDescription;
public String objectName;
}

The second is:

public class GameEvent
{
// data members
public int eventID;
public String eventDescription;
public int hasEventOccured;
}

The xml structure I am looking for is

<GAME>
    <EVENTS>
        <event>         
        </event>    
    <EVENTS>

<OBJECTS>
    <object>            
    </object>
<OBJECTS>

like image 250
jsomers89 Avatar asked Dec 29 '25 02:12

jsomers89


1 Answers

It can be done in a single expression, the parameters of the XElement constructor after its name are used to create children, and collections are expanded so a LINQ expression will create one child for each node (XElement creates a child element, XAttribute adds an attribute).

var content = new XElement("GAME",
                    new XElement("EVENTS",
                       from e in AllEvents
                       select new XElement("EVENT",
                              new XELement("eventID", e.eventId),
                              new XElement("eventDescription", e.eventDescription),
                              new XElement("hasEventOccured", e.hasEventOccured)
                       )
                    ),
                    new XElement("OBJECTS",
                       from obj in AllObjects
                       select new XElement("OBJECT",
                             // make content for a single object
                       )
                    ));
like image 149
Richard Avatar answered Dec 30 '25 14:12

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!