Reputation: 173
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>
Upvotes: 3
Views: 588
Reputation: 1771
Create the structure of your class like below: Create the structure of your class like below and the serialize the object of class by assigning value to its properties:
[XmlRoot("GAME")]
public class Game
{
[XmlElement("EVENTS")]
public Events Events { get; set; }
[XmlElement("OBJECTS")]
public GameObject GameObject { get; set; }
}
public class Events
{
[XmlElement("EVENTS")]
public GameEvent Event;
}
public class Object
{
[XmlElement("object")]
public GameObject GameObject;
}
public class GameEvent
{
[XmlElement("eventID")]
public int eventID;
[XmlElement("eventDescription")]
public String eventDescription;
[XmlElement("hasEventOccured")]
public int hasEventOccured;
}
public class GameObject
{
[XmlElement("squareID")]
public int squareID;
[XmlElement("objectID")]
public int objectID;
[XmlElement("objectDescription")]
public String objectDescription;
[XmlElement("objectName")]
public String objectName;
}
Upvotes: 0
Reputation: 32481
You can define another class like this:
[DataContract(Name ="GAME")]
public class Game
{
[DataMember(Name = "OBJECTS")]
List<GameObject> Objects { get; set; }
[DataMember(Name = "EVENTS")]
List<GameEvent> Events { get; set; }
}
Then using a generic method like this you can instantiated a new Game
and pass it this method:
public static void Serialize<T>(string path, T value)
{
System.Xml.Serialization.XmlSerializer serializer =
new System.Xml.Serialization.XmlSerializer(typeof(T));
System.Xml.XmlTextWriter writer =
new System.Xml.XmlTextWriter(path, System.Text.Encoding.UTF8);
serializer.Serialize(writer, value);
writer.Close();
}
If DataContract
attribute is not availabe, don't forget to add reference to System.Runtime.Serialization
.
Upvotes: 0
Reputation: 108975
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
)
));
Upvotes: 1