解析xml格式轉為對象


方法一

  using System.Xml;
  using System.Reflection;

  XmlDocument xml = new XmlDocument();
  xml.LoadXml(result);
  //加載xml格式后最外部被response包含,因此需要獲取此節點的對應子節點
  var resultXml = xml.SelectSingleNode("/response").ChildNodes;
  //需要轉換的對象
  PayResponse responseResult = new PayResponse();
  //遍歷循環對象內容並賦值
  foreach(XmlNode item in resultXml)
  {
      foreach(PropertyInfo item2 in responseResult.GetType().GetProperties())
      {
          if(item.Name == item2.Name)
              responseResult.GetType().GetProperty(item2.Name).SetValue(responseResult, item.InnerText);
      }
  }

方法二

  using System.Xml;
  using System.Xml.Serialization;
  using System.IO;

  public static T GetXmlEntity<T>(string xml)
  {
      try
      {
          XmlDocument xmlDoc = new XmlDocument();
          xmlDoc.LoadXml(xml);
          var xmlResponse = xmlDoc.InnerXml;
          //若response節點之上還存在節點可用以下方法,如<main><response>...</response></main>
          //var xmlResponse = xmlDoc.SelectSingleNode("/main").InnerXml;
          XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute("response"));
          StringReader reader = new StringReader(xmlResponse);

          T res = (T)serializer.Deserialize(reader);
          reader.Close();
          reader.Dispose();
          return res;
      }
      catch(Exception)
      {
          throw new ResultException("Format error!");
      }

  }

  public void main(){
      //將result返回的內容直接轉換為PayResponse對象
      var responseResult = This.GetXmlEntity<PayResponse>(result);
  }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM