解析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);
  }  

posted @ 2021-11-15 11:50  贰竹  阅读(1704)  评论(0编辑  收藏  举报