2015-07-23 3 views
1

У меня есть скрипт, который подключается к api, получает заказы и записывает xml в файл.C# xml to csv api results

Как бы я начал писать это вместо csv?

вот пример кода

private void button1_Click(object sender, EventArgs e) 
{ 
    string developerKey = string.Empty; 
    string password = string.Empty; 
    string accountID = string.Empty; 

    developerKey = "xxxxx"; 
    password= "xxxxx"; 
    accountID = "xxxxx"; 

    OrderCriteria criteria = new OrderCriteria(); 
    criteria.StatusUpdateFilterBeginTimeGMT = DateTime.UtcNow.AddDays(-30); 
    criteria.StatusUpdateFilterEndTimeGMT = DateTime.UtcNow; 

    // this would be like a Ready-To-Ship Report 
    criteria.PaymentStatusFilter = "Cleared"; 
    criteria.ShippingStatusFilter = "Unshipped"; 

    criteria.ExportState = "NotExported"; 
    criteria.DetailLevel = "Complete"; 
    criteria.PageSize = 20; 

    OrderService orderService = new OrderService(); 
    orderService.APICredentialsValue = new APICredentials(); 
    orderService.APICredentialsValue.DeveloperKey = developerKey; 
    orderService.APICredentialsValue.Password = password; 

    try 
    { 
     criteria.PageNumberFilter = 1; 
     while(true) 
     { 
      APIResultOfArrayOfOrderResponseItem orderResponse = orderService.GetOrderList(accountID, criteria); 

      if (orderResponse.Status == ResultStatus.Failure) 
      { 
       throw new Exception(orderResponse.Message); 
      } 

      if (orderResponse.ResultData.Length == 0) 
       break; // we moved outside the pages that have data on them 

      List<string> clientOrderIdentifiers = new List<string>(); 
      XmlSerializer serializer = new XmlSerializer(typeof(OrderResponseDetailComplete)); 
      XmlTextWriter writer = null; 
      foreach(OrderResponseItem order in orderResponse.ResultData) 
      { 
       OrderResponseDetailComplete completeOrder = order as OrderResponseDetailComplete; 
       //put the order on the disk as its own file 
       using (writer = new XmlTextWriter(string.Format(@"C:\orders\{0}.xml", completeOrder.ClientOrderIdentifier), System.Text.Encoding.UTF8)) 
       { 
        serializer.Serialize(writer, completeOrder); 
       } 
       //keep the ClientOrderIdentifier so we can send a batch to mark the orders as exported, filtering the orders from future queries 
       clientOrderIdentifiers.Add(completeOrder.ClientOrderIdentifier); 
      } 

      //submit our batch of processed orders 
      APIResultOfArrayOfBoolean exportStatusResponse = orderService.SetOrdersExportStatus(accountID, clientOrderIdentifiers.ToArray(), true); 

      if (exportStatusResponse.Status == ResultStatus.Failure) 
      { 
       throw new Exception(exportStatusResponse.Message); 
      } 

      //make sure each order was succesfully updated 
      for (int responseCount = 0; responseCount < exportStatusResponse.ResultData.Length; ++responseCount) 
      { 
       if (exportStatusResponse.ResultData[responseCount] == false) 
       { 
        //order was not successfully marked as exported 
        MessageBox.Show("Order was not successfully marked as exported:" + orderResponse.ResultData[responseCount].ClientOrderIdentifier); 
       } 
      } 
      ++criteria.PageNumberFilter; 
     } 
    } 
    catch (Exception ex) 
    { // big catch for the entire function 
     MessageBox.Show(ex.ToString()); 
    } 
} 

мне нужна только некоторые из XML, а также.

В настоящее время он загружает каждый заказ и записывает его в отдельный файл. Я просто хочу, чтобы все было в одном файле идеально.

Благодаря

ответ

1

Вы можете использовать Service Stack, быстрый JSON .NET, в JSV и CSV Текст сериализаторы (more info) или другие подобные CsvHelper найти библиотеки.

только для сериализации заказов, вы заинтересованы в, сначала выберите их с linq:

var orders = orderResponse .Select(order => order.SomeProperty && ..) orders.ToCsv().Print();

+0

спасибо за помощь – rob