简体   繁体   中英

ASP.NET - How to Transfer to XML File

What would be the easier way to transfer the code below into an XML File. I have tried to use XDocument, but the code gets very confusing with all of the if statments.

My Code:

public class GetReportListSample
{


    public static void InvokeGetReportList(AmazonWebService service, GetReportListRequest request)
    {
        try
        {
            GetReportListResponse response = service.GetReportList(request);
            HttpContext.Current.Response.Write("=======STARTING REQUEST===================");

            if (response.IsSetGetReportListResult())
            {
                HttpContext.Current.Response.Write("            GetReportListResult");
                GetReportListResult getReportListResult = response.GetReportListResult;

                if (getReportListResult.IsSetNextToken())
                {
                     HttpContext.Current.Response.Write("                NextToken");
                     HttpContext.Current.Response.Write(""+ getReportListResult.NextToken);
                }

                if (getReportListResult.IsSetHasNext())
                {
                     HttpContext.Current.Response.Write("                HasNext");
                     HttpContext.Current.Response.Write("" + getReportListResult.HasNext);

                }


                List<ReportInfo> reportInfoList = getReportListResult.ReportInfo;
                foreach (ReportInfo reportInfo in reportInfoList)
                {
                     HttpContext.Current.Response.Write("                ReportInfo");
                     amzXML1.Add(new XElement("ReportInfo", ""));

                    if (reportInfo.IsSetReportId())
                    {
                         HttpContext.Current.Response.Write("                    ReportId");
                         HttpContext.Current.Response.Write("" +  reportInfo.ReportId);

                    }
                    if (reportInfo.IsSetReportType())
                    {
                         HttpContext.Current.Response.Write("                    ReportType");
                         HttpContext.Current.Response.Write("" +  reportInfo.ReportType);

                    }
                    if (reportInfo.IsSetReportRequestId())
                    {
                         HttpContext.Current.Response.Write("                    ReportRequestId");
                         HttpContext.Current.Response.Write("" +  reportInfo.ReportRequestId);

                    }
                    if (reportInfo.IsSetAvailableDate())
                    {
                         HttpContext.Current.Response.Write("                    AvailableDate");
                         HttpContext.Current.Response.Write("" +  reportInfo.AvailableDate);

                    }
                    if (reportInfo.IsSetAcknowledged())
                    {
                         HttpContext.Current.Response.Write("                    Acknowledged");
                         HttpContext.Current.Response.Write("" +  reportInfo.Acknowledged);

                    }
                    if (reportInfo.IsSetAcknowledgedDate())
                    {
                         HttpContext.Current.Response.Write("                    AcknowledgedDate");
                         HttpContext.Current.Response.Write("" +  reportInfo.AcknowledgedDate);

                    }
                }
            }
            if (response.IsSetResponseMetadata())
            {
                 HttpContext.Current.Response.Write("            ResponseMetadata");
                ResponseMetadata responseMetadata = response.ResponseMetadata;
                if (responseMetadata.IsSetRequestId())
                {
                     HttpContext.Current.Response.Write("                RequestId");
                     HttpContext.Current.Response.Write("" + responseMetadata.RequestId);
                }
            }

             HttpContext.Current.Response.Write("            ResponseHeaderMetadata");
             HttpContext.Current.Response.Write("                RequestId");
             HttpContext.Current.Response.Write("                    " + response.ResponseHeaderMetadata.RequestId);
             HttpContext.Current.Response.Write("                ResponseContext");
             HttpContext.Current.Response.Write("                    " + response.ResponseHeaderMetadata.ResponseContext);
             HttpContext.Current.Response.Write("                Timestamp");
             HttpContext.Current.Response.Write("                    " + response.ResponseHeaderMetadata.Timestamp);

        }
        catch (MarketplaceWebServiceException ex)
        {
             HttpContext.Current.Response.Write("Caught Exception: " + ex.Message);
             HttpContext.Current.Response.Write("Response Status Code: " + ex.StatusCode);
             HttpContext.Current.Response.Write("Error Code: " + ex.ErrorCode);
             HttpContext.Current.Response.Write("Error Type: " + ex.ErrorType);
             HttpContext.Current.Response.Write("Request ID: " + ex.RequestId);
             HttpContext.Current.Response.Write("XML: " + ex.XML);
             HttpContext.Current.Response.Write("ResponseHeaderMetadata: " + ex.ResponseHeaderMetadata);
        }
    }
}

This is how the XML SHOULD look(keep in mind, that there may be several ReportInfo elements:

<?xml version="1.0"?>
<GetReportListResponse xmlns="http://mws.amazonservices.com/doc/2009-01-01/">
  <GetReportListResult>
  <NextToken>2YgYW55IPQhvu5hbCBwbGVhc3VyZS4=</NextToken>
    <HasNext>true</HasNext>
    <ReportInfo>
      <ReportId>898899473</ReportId>
      <ReportType>_GET_MERCHANT_LISTINGS_DATA_</ReportType>
      <ReportRequestId>2278662938</ReportRequestId>
      <AvailableDate>2009-02-10T09:22:33+00:00</AvailableDate>
      <Acknowledged>false</Acknowledged>
    </ReportInfo>
  </GetReportListResult>
  <ResponseMetadata>
    <RequestId>fbf677c1-dcee-4110-bc88-2ba3702e331b</RequestId>
  </ResponseMetadata>
</GetReportListResponse>  

Based on your question what I understand is you need XML file as downloadable content, is this understanding correct? How about making your own plain entity or data structure [C#/VB Class with [properties get/set]?

What I mean is, once you have .net object you just assign value to its properties and take the advantage of .Net Serialization [XML or JSON whatever you need], put the serialized content in HTTPResponse object and specify the response content type.

From above sample structure XML, elements will become your fields or properties inside class. Hint: If you have sample XML structure then convert to XSD and use XSD command line utility to generate .net class [VB or C#]. Do not forget to mark you classes with serialize attribute [Serializable] if you write manually.

Below is the sample of code for serialization, convert this code to your helper method.

Object value = someobject; //Serializable object

XmlSerializer serializer = new XmlSerializer(value.GetType());
string xmlString;   // will contain XML string
StringWriter xmlStringWriter = null;  // String writer;
XmlWriter xmlWriter = null; // XML writer.

XmlWriterSettings writerSettings = new XmlWriterSettings  //XML writer settings
{
    OmitXmlDeclaration = true,
    NewLineOnAttributes = true
};
XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);// Remove namespaces of XML declaration.
try
{
    xmlStringWriter = new StringWriter(CultureInfo.CurrentCulture);
    xmlWriter = XmlWriter.Create(xmlStringWriter, writerSettings);
    serializer.Serialize(xmlWriter, value, xmlNamespace);
    xmlString = Convert.ToString(xmlStringWriter);
}
finally
{
    if (xmlStringWriter != null)
    {
        xmlStringWriter.Dispose();
    }
}

Hope this will help you to remove lengthy code with negligible trade-off of resource consumption cost during serialization. Any way .Net do use serialization to get the content out from Page object to response object so if thing are properly done then no issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM