zoukankan      html  css  js  c++  java
  • C# 对xml进行操作

    一: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:APINewSabreApiSabre.ApiTestWinFormXml"; //此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;    }     }   }
  • 相关阅读:
    httprunner-2-linux下搭建hrun(下)
    Docker学习3-简单shell脚本安装mysql5.7与docker小技巧
    功能测试--聊天功能测试&微信聊天
    Fiddler抓包3-查看get与post请求
    面向对象--继承
    Mybatis入门
    Maven基础
    Cookie&Session
    Redis应用
    Redis概念和安装
  • 原文地址:https://www.cnblogs.com/lubolin/p/6373437.html
Copyright © 2011-2022 走看看