Model与XML互相转换

前端之家收集整理的这篇文章主要介绍了Model与XML互相转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
interface ISerialize
    {
        /// <summary>
        /// xml 转换为 model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        T XmlToModel<T>(string xml,T model);


        /// <summary>
        /// model 转换为xml
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        string ModelToXml<T>(T model);


        /// <summary>
        /// xml 转换为Table
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        DataTable XmlToTable(string xml);


        /// <summary>
        /// 获取对应XML节点的值
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        string XmlAnalysis(string stringRoot,string xml);
    }




public class Serialize:ISerialize
    {

        public T XmlToModel<T>(string xml,T model)
        {
            StringReader xmlReader = new StringReader(xml);
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            return (T)xmlSer.Deserialize(xmlReader);
        }

        public string ModelToXml<T>(T model)
        {
            MemoryStream stream = new MemoryStream();
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            xmlSer.Serialize(stream,model);

            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }


        public System.Data.DataTable XmlToTable(string xml)
        {
            StringReader xmlReader = new StringReader(xml);
            DataSet ds = new DataSet();
            ds.ReadXml(xmlReader);
            return ds.Tables[0];
        }


        public string XmlAnalysis(string stringRoot,string xml)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            return doc.DocumentElement.SelectSingleNode(stringRoot).InnerXml.Trim();
        }
    }
 
ISerialize s = new Serialize();
      //把XML文件转换为对应的实体类


      string xml = @"<Depart>
              <DepartID>123</DepartID>
              <PerSons>
                <PerSon>
                  <name>张三</name>
                  <age>3</age>
                </PerSon>
                <PerSon>
                  <name>李斯</name>
                  <age>56</age>
                </PerSon>
              </PerSons>
            </Depart>";




      //var info = s.XmlToModel<Depart>(xml,new Depart());


     // string newXml = s.ModelToXml<Depart>(info);
     // var Info = (Depart)XmlUtil.Deserialize(typeof(Depart),xml);
      s.XmlToTable(xml);
原文链接:https://www.f2er.com/xml/296811.html

猜你在找的XML相关文章