C# XML 序列化、反序列化、泛型、zip压缩文件 解析样例

XML 和 SOAP 序列化

XML 节点/属性
[XmlRoot("root", IsNullable = false)]
[XmlElement("names")]
[XmlElement(ElementName = "string")]
[XmlElement("string")]
[XmlIgnore]
[XmlType("content")]
[XmlType(TypeName = "item")]
[XmlAttribute]
[XmlText]
[XmlArray("params")]
[XmlIgnore]
[XmlInclude]
<![CDATA[]]>

XML 类
XmlDocument
XmlElement
XmlNamespaceManager
XmlNode

XML 方法
SelectSingleNode("")
SelectSingleNode("/")
SelectSingleNode("//")

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"D:\1.xml")//Load加载XML文件
xmlDoc.LoadXml(@"D:\1.xml")//LoadXML加载XML字符串

1、XML序列化工具类

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

namespace WebApplication1.App_Start
{
    public static class XmlUtil
    {
        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineChars = "\r\n";
                settings.Encoding = encoding;
                settings.IndentChars = "  ";
                settings.OmitXmlDeclaration = true;

                using (XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    //Create our own namespaces for the output
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    //Add an empty namespace and empty value
                    ns.Add("", "");
                    serializer.Serialize(writer, o, ns);
                    writer.Close();
                }

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// 从XML字符串中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="s">包含对象的XML字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize<T>(string s, Encoding encoding)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentNullException("s");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
            {
                using (StreamReader sr = new StreamReader(ms, encoding))
                {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }

        /// <summary>
        /// 将一个对象按XML序列化的方式写入到一个文件
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="path">保存文件路径</param>
        /// <param name="encoding">编码方式</param>
        public static void XmlSerializeToFile(object o, string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineChars = "\r\n";
                settings.Encoding = encoding;
                settings.IndentChars = "    ";

                using (XmlWriter writer = XmlWriter.Create(file, settings))
                {
                    serializer.Serialize(writer, o);
                    writer.Close();
                }
            }
        }

        /// <summary>
        /// 读入一个文件,并按XML的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            string xml = File.ReadAllText(path, encoding);
            return XmlDeserialize<T>(xml, encoding);
        }
    }
}

2、泛型

    public class Test : IRequestModel
    {
        public string aaa1 { get; set; }
        public string aaa2 { get; set; }
        public string aaa3 { get; set; }
        public string aaa4 { get; set; }
        public string aaa5 { get; set; }
    }

    public interface IRequestModel
    {
    }

    [XmlRoot("CPMB2B")]
    public class RequestObj<T> where T : IRequestModel
    {
        public RequestMessageData<T> MessageData { get; set; }
    }

    public class RequestMessageData<T> where T : IRequestModel
    {
        public ModelBase Base { get; set; }
        public RequestHeader ReqHeader { get; set; }
        public T DataBody { get; set; }
    }

    public class RequestHeader
    {
        public RequestHeader() { }
        public RequestHeader(string merchantNo, string transCode, string transCodeId)
        {
            ClientTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            MerchantNo = merchantNo;
            TransCode = transCode;
            TransCodeId = transCodeId;
        }
        public string ClientTime { get; set; }
        public string MerchantNo { get; set; }
        public string TransCodeId { get; set; }
        public string TransCode { get; set; }
    }

    public class ModelBase
    {
        /// <summary>
        /// 版本号,交易时要判断版本匹配
        /// </summary>
        public string Version { get; set; } = "2.3";

        /// <summary>
        /// 签名标志:0=未包含签名;1=包含签名
        /// </summary>
        public string SignFlag { get; set; } = "1";

        /// <summary>
        /// 服务模式:3=支付存管系统(PDS)
        /// </summary>
        public string SeverModel { get; set; } = "3";
    }

3、Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.IO.Compression;
using System.Configuration;
using System.Xml.Serialization;
using WebApplication1.App_Start;
using System.Text;

namespace WebApplication1.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            try
            {
                string fileName = $@"BATCH_PAY_{DateTime.Now.ToString("yyyyMMddHHmmss")}_01.DAT";

                RequestObj<Test> a = new RequestObj<Test>();
                a.MessageData = new RequestMessageData<Test>();
                a.MessageData.Base = new ModelBase();
                a.MessageData.DataBody = new Test
                {
                    aaa1 = "1",
                    aaa2 = "2",
                    aaa3 = "3",
                    aaa4 = "4"
                };

                string xml = XmlUtil.XmlSerialize(a, Encoding.UTF8);

                WriteFile(fileName, "test test");

                string filePath = $@"{WebRoot()}DAT\{fileName}";
                string datPath = $@"{WebRoot()}DAT";
                string zipPath = $@"D:\web\zip\{fileName}.zip";
                string extractPath = @"D:\MyFile\example";

                //将整个文件夹压缩为ZIP文件 
                ZipFile.CreateFromDirectory(datPath, zipPath);
                System.IO.File.Delete(filePath);

                //读取压缩文件信息
                if (System.IO.File.Exists(zipPath))
                {
                    var data = ZipFile.OpenRead(zipPath);
                    using (var stream = data.Entries[0].Open())
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            var str = sr.ReadToEnd();
                            var list = str.Split(Environment.NewLine.ToCharArray()).ToList();
                        }
                    }
                }

                //解压ZIP文件到extrat目录中。 
                //ZipFile.ExtractToDirectory(zipPath, extractPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return View();
        }


        public void WriteFile(string fileName, string content)
        {
            string path = string.Empty;
            var current = System.Web.HttpContext.Current;
            //在网站根目录下创建日志目录 
            if (current == null)
                path = ConfigurationManager.AppSettings["WebLogPath"].ToString();
            else
                path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "DAT";
            if (!Directory.Exists(path))//如果日志目录不存在就创建  
            {
                Directory.CreateDirectory(path);
            }
            string filePath = $"{path}/{fileName}";//用日期对日志文件命名  
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间  

            //创建或打开日志文件,向日志文件末尾追加记录  
            using (StreamWriter mySw = System.IO.File.AppendText(filePath))
            {
                //向日志文件写入内容  
                string write_content = time + " " + content;
                mySw.WriteLine(write_content);

                //关闭日志文件  
                mySw.Close();
            }
        }

        public string WebRoot()
        {
            string path = string.Empty;
            var current = System.Web.HttpContext.Current;
            //在网站根目录下创建日志目录 
            if (current == null)
                path = ConfigurationManager.AppSettings["WebLogPath"].ToString();
            else
                path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
            if (!Directory.Exists(path))//如果日志目录不存在就创建  
            {
                Directory.CreateDirectory(path);
            }

            return path;
        }
    }
}

.NET Core XML 数据解析
案例1【调用天气预报的webservice,解析ArrayOfString中string数组】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
    #region
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("byProvinceName", "河北");

    string url134 = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity";
    string param123 = StringPlus.DictionaryToString(dict);
    QDHttpClient clientWeather123 = new QDHttpClient((int)EnumContentType.urlencoded, url134, param123);
    string xmlWeather123 = clientWeather123.ExecutePost();

    xmlWeather123 = xmlWeather123.Replace("http://WebXml.com.cn/", "");

    var itemList = XmlUtils.XmlDeserialize<ArrayOfString>(xmlWeather123, Encoding.Default);
    #endregion
}

[System.Xml.Serialization.XmlRootAttribute("ArrayOfString", IsNullable = false)]
public class ArrayOfString
{
    [XmlElement("string")]
    public List<string> string123 { get; set; }
}

案例2【解析string数组,嵌套关系】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
  #region
  string aaaa = "<?xml version=\"1.0\"?><root><barcodes><barcode>AAA</barcode></barcodes></root>";
  var uu = XmlUtils.XmlDeserialize<DownLoadPDFRequest>(aaaa, Encoding.UTF8);
  #endregion
}

[XmlRoot("root", IsNullable = false)]
public class DownLoadPDFRequest
{
  [XmlElement("barcodes")]
  public barcoders barcodes { get; set; }
}

[System.Xml.Serialization.XmlRootAttribute("ArrayOfString", IsNullable = false)]
public class DownLoadPDFRequest666
{
  [XmlElement("string")]
  public List<string> barcode123 { get; set; }
}

案例3【解析string数组】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
  #region
  string aa1 = "<?xml version=\"1.0\"?><root><barcode>AAA</barcode><barcode>BBB</barcode></root>";
  var uu1 = XmlUtils.XmlDeserialize<DownLoadPDFRequest123>(aa1, Encoding.UTF8);
  #endregion
}

[System.Xml.Serialization.XmlRootAttribute("root", IsNullable = false)]
public class DownLoadPDFRequest123
{
  [XmlElement("barcode")]
  public List<string> barcode123 { get; set; }
}

案例4【解析string数组】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
  #region
  string aaw = "<?xml version=\"1.0\"?><ArrayOfString xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\"><string>石家庄 (53698)</string><string>BBB</string></ArrayOfString>";
  var uuw = XmlUtils.XmlDeserialize<DownLoadPDFRequest666>(aaw, Encoding.UTF8);
  #endregion
}

[System.Xml.Serialization.XmlRootAttribute("ArrayOfString", IsNullable = false)]
public class DownLoadPDFRequest666
{
  [XmlElement("string")]
  public List<string> barcode123 { get; set; }
}

案例5【解析User信息】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
  #region User 反序列化
  string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><User><code>11</code><name>kkkk</name></User>";
  User u = XmlUtils.XmlDeserialize<User>(xmlString, Encoding.UTF8);
  #endregion
}

[Serializable]
public class User
{
  public int code { get; set; }

  public string name { get; set; }
}

案例6【xmlnode 读取 User信息 InnerText】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
  #region xmlnode 读取 User信息
  XmlDocument xmlDocUser = new XmlDocument();
  xmlDocUser.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><User><code>11</code><name>kkkk</name></User>");
  XmlNode rootNodeUser = xmlDocUser.SelectSingleNode("User");
  foreach (XmlNode xxNode in rootNodeUser.ChildNodes)
  {
    string key = xxNode.Name;
    string value = xxNode.InnerText;
  }
  #endregion

  #region
  QDHttpClient client = new QDHttpClient((int)EnumContentType.xml, "http://192.168.1.179:8111/WebService1.asmx/Test", "");
  string xml = client.ExecutePost();
  //string xml = <?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">{"code":1,"name":"abc"}</string>
 
  XmlDocument resultXml = new XmlDocument();
  resultXml.LoadXml(xml);
  string json = resultXml.InnerText;
  Company company = JsonConvert.DeserializeObject<Company>(json);
  #endregion
}

[Serializable]
public class Company
{
  public int code { get; set; }

  public string name { get; set; }
}

案例7【XmlNode InnerXml】

[HttpGet("api")]
public IEnumerable<WeatherForecast> GetApi()
{
  #region
  Dictionary<string, string> dictionary = new Dictionary<string, string>();
  dictionary.Add("byProvinceName", "河北");

  string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity";
  string param = StringPlus.DictionaryToString(dictionary);
  QDHttpClient clientWeather = new QDHttpClient((int)EnumContentType.urlencoded, url, param);
  string xmlWeather = clientWeather.ExecutePost();


  xmlWeather = xmlWeather.Replace("http://WebXml.com.cn/", "");

  XmlDocument xmlWeatherDoc = new XmlDocument();
  //xmlWeatherDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><ArrayOfString xmlns:xsi=\"http://www.w3
  xmlWeatherDoc.LoadXml(xmlWeather);
  XmlNodeList weatherList = xmlWeatherDoc.SelectNodes("/ArrayOfString");
  foreach (XmlNode weatherNode in weatherList)
  {
    string value = weatherNode.InnerXml;
  }
}

案例8【XML节点/属性】

[HttpGet()]
public IEnumerable<WeatherForecast> Get()
{
    #region 对象序列化字符串
    XML_root root = new XML_root();
    root.template = "这里填写内容";
    string strxml = XmlUtils.XmlSerialize(root, Encoding.UTF8);
    #endregion

    #region 字符串序列号对象
    string xmlString = "<?xml version=\"1.0\"?><XML_root><content><SPCX tablename=\"S_XS\" type=\"varchar\">0001号</SPCX ><JBFY tablename=\"S_XS\" type=\"varchar\" /></content><template>这里填写内容</template></XML_root>";
    var result = XmlUtils.XmlDeserialize<XML_root>(xmlString, Encoding.UTF8);
    #endregion
}

定义对象、属性

public class XML_root
{
    /// <summary>
    /// 
    /// </summary>
    public string template { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public XML_content content = new XML_content();
    
    /// <summary>
    /// 
    /// </summary>
    [XmlIgnore]
    public List<XML_AchDetail> listdetail = new List<XML_AchDetail>();
}

[XmlType("content")]
public class XML_content
{
    public NAttribute SPCX = new NAttribute { value = "123333" };
    public NAttribute JBFY = new NAttribute();
    public NAttribute ABCD = new NAttribute { tablename="USER"};
}

public class NAttribute
{
    [System.Xml.Serialization.XmlAttribute]
    public string tablename = "S_XS";

    [System.Xml.Serialization.XmlAttribute]
    public string type = "varchar";

    [System.Xml.Serialization.XmlText]
    public string value { get; set; }
}

public class XML_AchDetail
{
    [System.Xml.Serialization.XmlText]
    public string value { get; set; }
}

*

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值