C# xml轉換成對象

來源:互聯網
上載者:User

標籤:轉換   tco   val   new   ade   namespace   env   line   odi   

C#內部封裝的類庫"namespace System.Net.Http   class HttpClient",

(1)此內部有進行請求所用的方法此處用得時Post的非同步請求,此時的要求標頭是固定的先忽略

  public class Post

  {

    private static readonly HttpClient _httpClient; //建立類庫成員變數,以注入的方式進行方法調用

     public async Task<string> PostAsync(string fileName, string url = "https://webservices3.sabre.com")
          {
              string result = string.Empty;
              try
              {
                  StreamReader sr = new StreamReader(fileName, Encoding.UTF8); //以一種特定的編碼用位元組流讀取字元
                  string postContent = sr.ReadToEnd(); //從當前位置到末尾讀取全部位元組
                  sr.Close(); //關閉流
                  StringContent httpContent = new StringContent(postContent, Encoding.UTF8, "text/xml"); //基於字串建立HTTP新執行個體,即將資料內容以特定編碼寫成特定格式的字串新執行個體
                  var response = await _httpClient.PostAsync(url, httpContent); //以非同步作業將 POST 請求發送給指定 URI,返回非同步作業的任務對象(此對象形式根據請求文檔規定可得到,此處為xml)
                  result = await response.Content.ReadAsStringAsync(); //擷取HTTP響應訊息內容並將內容寫入非同步流進行讀取,得到包含xml的字串(其存在節點,擁有xml文檔的一切特性)
              }
              catch (Exception ex)
              {
                  result = ex.Message;
              }
              return result;
          }

  }

 

小結:首先要搞清楚如果對方介面接受請求的資料包是xml形式的,即使它是文檔,也可以看做是有一種特定格式字串。首先是直接將請求資訊寫成xml檔案,然後用流讀取此檔案內容,使其轉換成包含xml的字串

(若對方要求將資料進行壓縮也只是提高傳輸速度)

(2)對於此返回資料可以利用節點的讀取進行有效資料的提取:

  1:此xml中包含哪些命名空間要得到

  2:從包含xml的字串中得到根結點

  3:利用Linq文法對此xml類型的字串進行提取有效資訊,並將這些資料賦給所需對象的執行個體

 

  public class Connect

  {

     private string xmlFilePath = @"F:\API\NewSabreApi\Sabre.Api\TestWinForm\Xml\"; //此Xml檔案夾下有好多xml檔案

    public void getData()

    {

      Post post=new Post();

      var response=post.PostAsync(xmlFilePath + "BargainFinderMaxRs.xml");

      //命名空間

       XNamespace xsi = "http://www.opentravel.org/OTA/2003/05";
              XNamespace soap_env = "http://schemas.xmlsoap.org/soap/envelope/";
              XNamespace eb = "http://www.ebxml.org/namespaces/messageHeader";
              XNamespace wsse = "http://schemas.xmlsoap.org/ws/2002/12/secext";

      try
              {

        //從包含xml的字串中得到根結點
                  XElement root = XElement.Parse(response); 

        #region 

        //根據節點提取資料並得到所要對象,此對象有可能是個對象集合,若要得到單個Segments對象需要對其進行遍曆

         var flightSegments = from flight in root.Elements(soap_env + "Body").Elements(xsi + "OTA_AirLowFareSearchRS")
                      .Elements(xsi + "PricedItineraries")
                      .Elements(xsi + "PricedItinerary")

             select new Segments
                                     {
                                         carrier = flight.Element(xsi + "OperatingAirline").Attribute("Code").IsNamespaceDeclaration ? null : (string)flight.Element(xsi +"OperatingAirline").Attribute("Code").Value,       
                                         depAirport = (string)flight.Element(xsi + "DepartureAirport").Attribute("LocationCode") == null ? null : (string)flight.Element(xsi + "DepartureAirport").Attribute("LocationCode"),
                                         depTime = DateTime.Parse(flight.Attribute("DepartureDateTime") == null ? null : flight.Attribute("DepartureDateTime").Value).ToString("yyyyMMddHHmm"),

              }

         foreach(var flight in flightSegments)

         {

            //此處便可得到Segments類型的單個對象執行個體

            //此時便可對此對象執行個體flight進行業務需求的操作

         }

       }

      catch (Exception ex)
              {
                  tbResult.Text = ex.Message;
              }

    }

  }

C# xml轉換成對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.