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;
              }

    }

  }

时间: 2024-08-04 18:25:38

C# xml转换成对象的相关文章

dom4j将xml转换成对象

package test; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.tree.DefaultAttribute; public

json字符串转换成对象,对象转换成json字符串

方法一: 程序集:  System.Web.Extensions; 命名空间:System.Web.Script.Serialization; 最重要的类:JavaScriptSerializer //实例化 JavaScriptSerializer js = new JavaScriptSerializer(); js.Serialize();//将对象转换成json字符串:    序列号 js.Deserialize();//将json字符串转换成对象:  反序列化 方法二: 程序集:New

C#将XML转换成JSON转换XML

原文:C#将XML转换成JSON转换XML using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Newtonsoft.Json; namespace JSonConverter { class Program { static void Main(string[] args) { string xml = "<Test>

在一般处理程序中,把Form Post过来的表单集合转换成对象 ,仿 MVC post,反射原理

using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Web; using WebSite.Models; namespace testWebuploader.Scripts.Plugin.webuploader_v0._1._2 { /// <summary> /

XML转换成数组方法

<?php function xmlToArray2($xml) { // 将XML转为array $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $array_data; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transition

在服务器端将XML转换成HTML

以下是在服务器上转换XML文件所需要的简单源代码: <% 'Load the XML set xml = Server.CreateObject("Microsoft.XMLDOM") xml.async = false xml.load(Server.MapPath("cd_catalog.xml")) 'Load the XSL set xsl = Server.CreateObject("Microsoft.XMLDOM") xsl.

json转换成对象

在json转换成对象时,json的key会与java 类的字段一一对应.如果没有映射上的java字段会在该数据类型上填充默认值,如int 0,String null 等. 没有映射的json key在程序结束后会用警告显示出来,告知程序员那个key值没有被映射上 import net.sf.json.JSONObject; public class MainClass { public static void main(String[] args) { TestJsonBean(); } /**

JavaScript实现将xml转换成html table

JavaScript实现将xml转换成html table表格的方法. function ConvertToTable(targetNode) {  // if the targetNode is xmlNode this line must be removed  // i couldnt find a way to parse xml string to xml node  // so i parse xml string to xml document  targetNode = targ

request请求转换成对象。

1)前端post数据过来,key和val键值对会有很多,这个时候往后端进行插值的时候,最好将这些键值对转换成对象进行处理. 使用common-beanutils 来将前端传递过来的map直接转换成对象. 依赖jar包: 前端代码的name属性要和后端bean对象属性一致! 1 <h1>测试POST</h1> 2 <form action="/bean" method="post"> 3 <input type="t