在C#中将对象转换为XML的问题

时间:2010-10-02 12:28:55

标签: c# xml serialization

我有以下结构

public class GraphData
    {
        private List<RecordPerDay> recordPerDay;

        public List<RecordPerDay> RecordPerDay
        {
            get { return recordPerDay; }
            set { recordPerDay = value; }
        }
    }


public class RecordPerDay
    {
        private string date;
        private List<Entry> entry;

        [XmlAttribute]
        public string Date
        {
            get { return date; }
            set { date = value; }
        }

        public List<Entry> Entry
        {
            get { return entry; }
            set { entry = value; }
        }
    }

上一代码生成以下XML

<GraphData>  
    <RecordPerDay>    

    <RecordPerDay Date="9/29/2010">      
     <Entry>        
      <Entry From="08:46:07" To="20:47:06" TypeId="1" /> 
      <Entry From="08:52:21" To="08:53:17" TypeId="1" />   
      <Entry From="09:00:00" To="14:00:00" TypeId="1" />    
     </Entry>    
    </RecordPerDay>    

    <RecordPerDay Date="9/30/2010"> 
       <Entry>        
        <Entry From="08:46:07" To="20:47:06" TypeId="1" />
        <Entry From="08:52:21" To="08:53:17" TypeId="1" />  
       </Entry>    

    </RecordPerDay>  

    </RecordPerDay>
</GraphData>

但我需要它采用以下格式

<GraphData>  
    <RecordPerDay Date="9/29/2010">      
      <Entry From="08:46:07" To="20:47:06" TypeId="1" /> 
      <Entry From="08:52:21" To="08:53:17" TypeId="1" />   
      <Entry From="09:00:00" To="14:00:00" TypeId="1" />    
    </RecordPerDay>    
    <RecordPerDay Date="9/30/2010"> 
        <Entry From="08:46:07" To="20:47:06" TypeId="1" />
        <Entry From="08:52:21" To="08:53:17" TypeId="1" />  
    </RecordPerDay>  
</GraphData>

请尽快帮助我

先谢谢

2 个答案:

答案 0 :(得分:2)

尝试使用RecordPerDay装饰Entry[XmlElement]属性:

[XmlElement]
public List<RecordPerDay> RecordPerDay
{
    get { return recordPerDay; }
    set { recordPerDay = value; }
}

...

[XmlElement]
public List<Entry> Entry
{
    get { return entry; }
    set { entry = value; }
}

答案 1 :(得分:0)

[XmlElement]public List<Entry> Entry

上方添加public List<RecordPerDay> RecordPerDay