一:xml的基本操作
(1)獲得xml文件中的數據
1 //創建xml文檔對象 2 3 XmlDocument xmlDoc = new XmlDocument(); 4 5 //將指定xml文件加載xml文檔對象上 6 xmlDoc.Load("D:/Documents/Visual Studio 2013/Projects/ReadXMLFile/ReadXMLFile/Customers.xml"); 7 8 //表示文檔中的單個節點 9 XmlNode node; 10 11 //選擇匹配 參數XPath 表達式的第一個 XmlNode。 12 node = xmlDoc.SelectSingleNode("config/username"); 13 14 //獲取或設置節點及其所有子節點的串聯值。 15 string username = node.InnerText; 16 node = xmlDoc.SelectSingleNode("config/password"); 17 string password = node.InnerText;
(2)將數據按照對應的字節逐個保存到另一個xml文件中
1 XmlDocument xmlDoc = new XmlDocument(); 2 3 xmlDoc.Load(path); 4 5 XmlNode node; 6 7 node = xmlDoc.SelectSingleNode("config/username"); 8 9 if (node == null) 10 11 { 12 13 //創建節點 14 15 XmlElement n = xmlDoc.CreateElement("username"); 16 17 //對節點屬性值進行賦值 18 19 n.InnerText = username; 20 21 //將所創節點添加到已有節點后面 22 23 xmlDoc.SelectSingleNode("config").AppendChild(n); 24 25 } 26 27 else 28 29 { 30 31 node.InnerText = username; 32 33 } 34 35 node = xmlDoc.SelectSingleNode("config/password"); 36 37 if (node == null) 38 39 { 40 41 XmlElement n = xmlDoc.CreateElement("password"); 42 43 n.InnerText = password; 44 45 xmlDoc.SelectSingleNode("config").AppendChild(n); 46 47 } 48 49 else 50 51 { 52 53 node.InnerText = password; 54 55 } 56 57 //將xml文檔對象保存到指定的xml文件中 58 59 xmlDoc.Save(Xpath);
(3)將包含xml的字符串保存為一個xml文件
1 StreamReader str = new StreamReader("D:/Documents/Visual Studio 2013/Projects/ReadXMLFile/ReadXMLFile/Customers.xml"); 2 string readerXML = str.ReadToEnd(); 3 str.Close(); 4 5 此三句代碼只是為了得到一個包含xml的字符串 6 7 //創建一個xml文檔 8 XmlDocument xDoc = new XmlDocument(); 9 //將指定字符串加載到xml文檔對象中 10 xDoc.LoadXml(readerXML); 11 12 //將xml文檔對象保存到指定文件中(若此文件不存在會自行創建) 13 xDoc.Save("D:/Documents/Visual Studio 2013/Projects/ReadXMLFile/ReadXMLFile/Response1.xml"); 14 15
二:下面是之前寫的一個項目中的一段代碼,其功能是將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; } } }