使用多个对象生成XML

时间:2015-09-24 16:01:16

标签: c# xml

我有多个对象类,我试图将它们转换为一个xml文档。

第一堂课是:

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

第二个是:

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

我正在寻找的xml结构是

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

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

3 个答案:

答案 0 :(得分:1)

可以在单个表达式中完成,XElement构造函数的名称后面的参数用于创建子项,集合被扩展,因此LINQ表达式将为每个节点创建一个子项{{1创建一个子元素,XElement添加一个属性)。

XAttribute

答案 1 :(得分:0)

您可以定义另一个类:

[DataContract(Name ="GAME")]
public class Game
{
    [DataMember(Name = "OBJECTS")]
    List<GameObject> Objects { get; set; }

    [DataMember(Name = "EVENTS")]
    List<GameEvent> Events { get; set; }
}

然后使用这样的通用方法,你可以实例化一个新的Game并传递给它这个方法:

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();
}

如果DataContract属性不可用,请不要忘记添加对System.Runtime.Serialization的引用。

答案 2 :(得分:0)

创建类的结构,如下所示: 像下面一样创建类的结构,并通过为其属性赋值来序列化类的对象:

[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;
    }