首页 > 代码库 > C# xml转换成对象

C# xml转换成对象

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转换成对象