将XML实例化为对象。
NEWCASE nEWCASE = (NEWCASE)XmlHelper.DeserializeFromXml(file.FullName, typeof(NEWCASE));
序列化对象进xml文件
对象要根据XML节点属性生成,其中之一方式就是复制XML文件在VS工具栏编辑选择黏贴为,就自动生成XML类。**加粗样式**
XmlHelper.SerializeXmlNew(xmlLocalFullPath, eWcaseSave);
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace CLZReportGen.CommonHelper
{
public class XmlHelper
{
// https://www.cnblogs.com/guogangj/p/7489218.html
/// <summary>
/// 保存文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static void SaveFileContent(string filePath, string content)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.WriteAllText(filePath, content, Encoding.Default);
}
catch (Exception)
{
}
}
/**/
/// <summary>
/// 获得xsd文件路径
/// </summary>
public static string GetSchemaPath
{
get
{
return "20130729.xsd";
}
}
/**/
/// <summary>
/// 获理节点
/// </summary>
/// <returns></returns>
public static System.Collections.Generic.List<XmlSchemaElement> GetDatas()
{
XmlSchemaSet xsSet = new XmlSchemaSet();
//xsSet.Add("http://www.w3.org/2001/XMLSchema", GetSchemaPath);
xsSet.Compile();
XmlSchema schema = null;
foreach (XmlSchema xs in xsSet.Schemas())
{
schema = xs;
}
System.Collections.Generic.List<XmlSchemaElement> elements = new System.Collections.Generic.List<XmlSchemaElement>();
foreach (XmlSchemaObject obj in schema.Elements.Values)
{
if (obj.GetType() == typeof(XmlSchemaElement))
{
elements.Add((XmlSchemaElement)obj);
}
}
return elements;
}
/**/
/// <summary>
/// 添加元素
/// </summary>
/// <param name="sourceXsd"></param>
/// <param name="titles"></param>
/// <param name="sourceXml"></param>
/// <param name="sourceNd"></param>
/// <param name="values"></param>
public static void AddElement(XmlSchemaObject sourceXsd, Hashtable titles, XmlDocument sourceXml, XmlNode sourceNd, string[] values)
{
if (sourceXsd.GetType() == typeof(XmlSchemaChoice))
{
XmlSchemaChoice choice = sourceXsd as XmlSchemaChoice;
decimal min = choice.MinOccurs;
foreach (XmlSchemaObject item in choice.Items)
{
if (item.GetType() == typeof(XmlSchemaElement))
{
string name = ((XmlSchemaElement)item).Name;
if (titles.ContainsKey(name))
{
XmlElement element = sourceXml.CreateElement(name);
// element.InnerText = ((Excel.Range)st.Cells[rowIndex, (int)titles[name]]).Value2.ToString();
element.InnerText = values[(int)titles[name]];
sourceNd.AppendChild(element);
}
}
else
{
AddElement(item, titles, sourceXml, sourceNd, values);
}
}
}
else if (sourceXsd.GetType() == typeof(XmlSchemaElement))
{
string name = ((XmlSchemaElement)sourceXsd).Name;
if (titles.ContainsKey(name))
{
XmlElement element = sourceXml.CreateElement(name);
element.InnerText = values[(int)titles[name]];
sourceNd.AppendChild(element);
}
}
else if (sourceXsd.GetType() == typeof(XmlSchemaSequence))
{
foreach (XmlSchemaObject childItem in ((XmlSchemaSequence)sourceXsd).Items)
{
if (childItem.GetType() == typeof(XmlSchemaElement))
{
string name = ((XmlSchemaElement)childItem).Name;
if (titles.ContainsKey(name))
{
XmlElement element = sourceXml.CreateElement(name);
element.InnerText = values[(int)titles[name]];
sourceNd.AppendChild(element);
}
}
else
{
AddElement(childItem, titles, sourceXml, sourceNd, values);
}
}
}
else
{
return;
}
}
/**/
/// <summary>
/// 获得元素
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static System.Collections.Generic.List<XmlSchemaElement> GetDataItem(string name)
{
System.Collections.Generic.List<XmlSchemaElement> arr = new System.Collections.Generic.List<XmlSchemaElement>();
XmlSchemaElement element = GetTableSchema(name);
if (element == null)
{
return null;
}
XmlSchemaComplexType complex = element.SchemaType as XmlSchemaComplexType;
XmlSchemaSequence sequence = complex.ContentTypeParticle as XmlSchemaSequence;
foreach (XmlSchemaObject obj in sequence.Items)
{
if (obj.GetType() == typeof(XmlSchemaElement))
{
XmlSchemaElement item = (XmlSchemaElement)obj;
arr.Add(item);
}
else
{
GetItem(arr, obj);
}
}
return arr;
}
public static void GetItem(System.Collections.Generic.List<XmlSchemaElement> arr, XmlSchemaObject obj)
{
if (obj.GetType() == typeof(XmlSchemaElement))
{
XmlSchemaElement item = (XmlSchemaElement)obj;
arr.Add(item);
}
else if (obj.GetType() == typeof(XmlSchemaChoice))
{
XmlSchemaChoice choice = obj as XmlSchemaChoice;
foreach (XmlSchemaObject child in choice.Items)
{
if (child.GetType() == typeof(XmlSchemaElement))
{
XmlSchemaElement item = child as XmlSchemaElement;
arr.Add(item);
}
else
{
GetItem(arr, child);
}
}
}
else if (obj.GetType() == typeof(XmlSchemaSequence))
{
XmlSchemaSequence sequence = obj as XmlSchemaSequence;
foreach (XmlSchemaObject child in sequence.Items)
{
if (child.GetType() == typeof(XmlSchemaObject))
{
XmlSchemaElement item = child as XmlSchemaElement;
arr.Add(item);
}
else
{
GetItem(arr, child);
}
}
}
else
{
return;
}
}
/**/
/// <summary>
/// 根据节点名获得节点
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static XmlSchemaElement GetTableSchema(string name)
{
XmlSchemaSet xsSet = new XmlSchemaSet();
xsSet.Add("http://www.w3.org/2001/XMLSchema", GetSchemaPath);
xsSet.Compile();
XmlSchema schema = null;
foreach (XmlSchema xs in xsSet.Schemas())
{
schema = xs;
}
XmlQualifiedName qf = new XmlQualifiedName(name, "http://www.w3.org/2001/XMLSchema");
if (schema.Elements.Contains(qf))
{
return (XmlSchemaElement)schema.Elements[qf];
}
return null;
}
static void XmlValidation(object sendor, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
throw e.Exception;
case XmlSeverityType.Warning:
throw e.Exception;
}
}
/**/
/// <summary>
/// 校验dom对象
/// </summary>
/// <param name="doc"></param>
/// <returns></returns>
public static string CheckDataXml(XmlDocument doc)
{
XmlSchemaSet xsd = new XmlSchemaSet();
xsd.Add("", GetSchemaPath);
doc.Schemas = xsd;
try
{
doc.Validate(new ValidationEventHandler(XmlValidation));
}
catch (Exception ex)
{
return ex.Message;
}
return null;
}
/// <summary>
/// Get all properties and set default value
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="item">Object</param>
public static void ReflctProperties<T>(T item)
{
PropertyInfo[] pty = typeof(T).GetProperties();
Type t = item.GetType();
if (pty != null)
{
foreach (PropertyInfo info in pty)
{
if (!info.CanWrite) continue;
if (info.GetValue(item, null) == null && info.PropertyType == typeof(string))
{
t.GetProperty(info.Name).SetValue(item, String.Empty, null);
}
// Type g = info.GetType();
// ReflctProperties<T>();
}
}
//Serialize<T>("c:\\1.xml", item);
}
public static object GetProperty<T>(T item, string PropertyName)
{
PropertyInfo propertyInfo = item.GetType().GetProperty(PropertyName);
if (propertyInfo != null)
{
return propertyInfo.GetValue(item, null);
}
return null;
}
/// <summary>
/// Serialize class instance to XML file
/// </summary>
/// <typeparam name="T">type</typeparam>
/// <param name="XMLFileToCreate">XMLFileToCreate</param>
/// <param name="instance">class instance</param>
public static void Serialize<T>(string XMLFilePath, T instance)
{
if (instance == null) return;
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StreamWriter sw = new StreamWriter(XMLFilePath, false, new UTF8Encoding(false)))
{
xs.Serialize(sw, instance);
sw.Close();
}
}
/// 序列化类到xml文档
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <param name="obj">类的对象</param>
/// <param name="filePath">xml文档路径(包含文件名)</param>
/// <returns>成功:true,失败:false</returns>
public static void SerializeCreateXML<T>(string filePath, T obj)
{
XmlWriter writer = null; //声明一个xml编写器
XmlWriterSettings writerSetting = new XmlWriterSettings //声明编写器设置
{
Indent = true,//定义xml格式,自动创建新的行
// Encoding = new UTF8Encoding(false),//编码格式
Encoding = Encoding.GetEncoding("GB2312")
};
try
{
//创建一个保存数据到xml文档的流
writer = XmlWriter.Create(filePath, writerSetting);
}
catch (Exception ex)
{
}
XmlSerializer xser = new XmlSerializer(typeof(T)); //实例化序列化对象
try
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xser.Serialize(writer, obj,ns); //序列化对象到xml文档
}
catch (Exception ex)
{
}
finally
{
writer.Close();
}
}
/// <summary>
/// xml 反序列化为数据集
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public static DataSet XmlToDataset(string filepath)
{
string xmlurl = filepath;
StreamReader sr = new StreamReader(xmlurl, Encoding.UTF8);
DataSet ds = new DataSet();
ds.ReadXml(sr);
sr.Close();
sr.Dispose();
return ds;
}
/// <summary>
/// 读取文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string GetFileContent(string filePath)
{
string result = "";
if (File.Exists(filePath))
{
result = File.ReadAllText(filePath);
}
return result;
}
/// <summary>
/// 去掉数据空行
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetContentWithNotEmptyLine(string path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader read = new StreamReader(fs, Encoding.Default);
string strReadline;
StringBuilder stringBuilder = new StringBuilder();
while ((strReadline = read.ReadLine()?.Trim()) != null)
{
if (strReadline == string.Empty || strReadline.StartsWith("//"))
{
continue;
}
stringBuilder.AppendLine(strReadline);
// strReadline即为按照行读取的字符串
}
fs.Close();
read.Close();
return stringBuilder.ToString();
}
/// <summary>
/// 将类对象序列化进xml
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="XMLFilePath"></param>
/// <param name="instance"></param>
public static void SerializeToXML<T>(string XMLFilePath, T instance)
{
if (instance == null) return;
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StreamWriter sw = new StreamWriter(XMLFilePath))
{
xs.Serialize(sw, instance, ns);
}
}
public static MemoryStream SerializeXml(object data)
{
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms, Encoding.GetEncoding("GB2312"));
XmlSerializer xz = new XmlSerializer(data.GetType());
xz.Serialize(sw, data);
return ms;
}
public static void SerializeXmlNew<T>(string XMLFilePath, T instance)
{
if (instance == null) return;
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms, Encoding.GetEncoding("GB2312"));
XmlSerializer xz = new XmlSerializer(instance.GetType());
xz.Serialize(sw, instance, ns);
FileStream fs = new FileStream(XMLFilePath, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs);
w.Write(ms.ToArray());
fs.Close();
ms.Close();
}
//public static string Serializer<T>(T serialObject) where T : class
//{
// try
// {
// XmlSerializer ser = new XmlSerializer(typeof(T));
// System.IO.MemoryStream mem = new MemoryStream();
// XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
// ser.Serialize(writer, serialObject);
// writer.Close();
// return Encoding.UTF8.GetString(mem.ToArray());
// }
// catch (Exception ex)
// {
// return null;
// }
//}
/ <summary>
/ 将对象转换为xml字符串
/ </summary>
/ <param name="data"></param>
/ <returns></returns>
//public static string SerializeToXmlString2(Model.Risk.PACKET data)
//{
// var XmlString = Serializer<Model.Risk.PACKET>(data);
// var soapHead = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soapenv:Header/><soapenv:Body>";
// XmlString = XmlString.Replace("<?xml version=\"1.0\"?>", soapHead);
// XmlString += "</soapenv:Body></soapenv:Envelope> ";
// return XmlString;
//}
//public static string d54d()
//{
// XmlAttributes samplePropertyAttributes = new XmlAttributes();
// samplePropertyAttributes.XmlIgnore = true;
// XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
// sampleClassAttributes.Add(typeof(SampleClass), "SampleProperty", samplePropertyAttributes);
// var serializer = new XmlSerialized(typeof(SampleClass), sampleClassAttributes);
// serializer.Serialize(stream, newData);
// stream.Close();
//}
/// <summary>
/// 将对象转换为xml字符串
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string SerializeToXmlString(object data)
{
//下面将一个对象序列化成一个Xml的字符串
XmlSerializer xs = new XmlSerializer(data.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, data, ns);//将一个对象序列化成XML保存在内存流中
//获取内存流中的字符串
var XmlString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
var soapHead = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soapenv:Header/><soapenv:Body>";
XmlString= XmlString.Replace("<?xml version=\"1.0\"?>", soapHead);
XmlString += "</soapenv:Body></soapenv:Envelope> ";
return XmlString;
}
/// <summary>
/// 将对象转换为xml字符串
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string NewSerializeToXmlString(object data)
{
string XmlString = string.Empty;
using (MemoryStream output = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(data.GetType());
serializer.WriteObject(output, data);
// XmlString = encode.GetString(output.ToArray());
XmlString = Encoding.UTF8.GetString(output.ToArray());
}
// return result;
下面将一个对象序列化成一个Xml的字符串
//XmlSerializer xs = new XmlSerializer(data.GetType());
//XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//ns.Add("", "");
//MemoryStream ms = new MemoryStream();
//xs.Serialize(ms, data, ns);//将一个对象序列化成XML保存在内存流中
// //获取内存流中的字符串
//var XmlString = Encoding.UTF8.GetString(ms.ToArray());
//ms.Close();
var soapHead = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <soapenv:Header/><soapenv:Body>";
XmlString = XmlString.Replace("<?xml version=\"1.0\"?>", soapHead);
XmlString += "</soapenv:Body></soapenv:Envelope> ";
return XmlString;
}
/// <summary>
/// 处理忽略指定对象的指定属性
/// </summary>
/// <param name="obj"></param>
/// <param name="attName"></param>
public void XmlIgnoreAttribute(Object obj,string attName)
{
//XmlAttributes samplePropertyAttributes = new XmlAttributes();
//samplePropertyAttributes.XmlIgnore = true;
//XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
//sampleClassAttributes.Add(typeof(Stu), "Age1", samplePropertyAttributes);
//var dd2 = new Stu() { Age1 = "1", Age2 = "2" };
//StuNew newData = new StuNew();
//newData.Stu = dd2;
//newData.Name = "张三";
//string fileFullPath = "fo234o.xml";
//Stream stream = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write, FileShare.Read);
//var serializer = new XmlSerializer(typeof(StuNew), sampleClassAttributes);
//serializer.Serialize(stream, newData);
//stream.Close();
//XmlAttributes samplePropertyAttributes = new XmlAttributes();
//samplePropertyAttributes.XmlIgnore = true;
//XmlAttributeOverrides sampleClassAttributes = new XmlAttributeOverrides();
//sampleClassAttributes.Add(typeof(Stu), "Age1", samplePropertyAttributes);
//var dd2 = new Stu() { Age1 = "1", Age2 = "2" };
//StuNew newData = new StuNew();
//newData.Stu = dd2;
//newData.Name = "张三";
//string fileFullPath = "fo234o.xml";
//Stream stream = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write, FileShare.Read);
//var serializer = new XmlSerializer(typeof(StuNew), sampleClassAttributes);
//serializer.Serialize(stream, newData);
//stream.Close();
}
/// <summary>
/// 反序列化对象
/// </summary>
/// <param name="path"></param>
/// <param name="object_type"></param>
/// <returns></returns>
public static object DeserializeFromXml(string path, Type object_type)
{
try
{
XmlSerializer serializer = new XmlSerializer(object_type);
using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
{
return serializer.Deserialize(reader);
}
}
catch (Exception exp)
{
return null;
}
}
/// <summary>
/// 反序列化对象
/// </summary>
/// <param name="path"></param>
/// <param name="object_type"></param>
/// <returns></returns>
public static object DeserializeDataFromXml(string content, Type object_type)
{
MemoryStream memoryStream = new MemoryStream(); //创建其支持存储区为内存的流。
UnicodeEncoding uniEncoding = new UnicodeEncoding();
byte[] string1 = uniEncoding.GetBytes(content); //转化为字节
memoryStream.Write(string1, 0, string1.Length); //写入流
XmlSerializer serializer = new XmlSerializer(object_type);
using (StreamReader reader = new StreamReader(memoryStream, Encoding.Default))
{
return serializer.Deserialize(reader);
}
}
/// <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>
/ 反序列化对象
/ </summary>
/ <param name="path"></param>
/ <param name="object_type"></param>
/ <returns></returns>
//public static object DeserializeDataFromXml2(string content, Type object_type)
//{
// XmlSerializer xs = new XmlSerializer(object_type);
// MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(content));
// var p1 = xs.Deserialize(ms1) as typeof( object_type);
// ms1.Close();
//}
// MemoryStream ms = new MemoryStream();
//29 // XmlTextWriter textWriter = new XmlTextWriter(ms, Encoding.GetEncoding("UTF-8"));
//30 StreamWriter textWriter = new StreamWriter(ms, Encoding.GetEncoding("gb2312"));
//31 XmlSerializer serializer = new XmlSerializer(typeof(CISP.Message.Entity.DYAreaTypeMessage));
//32 serializer.Serialize(textWriter, dyArea);
//33
//34 string xmlMessage = Encoding.UTF8.GetString(ms.GetBuffer());
//35 isSerializer = true;
//36 ms.Close();
//37 textWriter.Close();
//38 return xmlMessage;
/ <summary>
/ 数据输入,反序列化xml为对象
/ </summary>
/ <param name="XmlString"></param>
/ <returns></returns>
//public string FileInput(string XmlString)
//{
// string InputResult = "";
// using (MemoryStream MS = new MemoryStream(Encoding.UTF8.GetBytes(XmlString)))
// {
// using (XmlReader xr = XmlReader.Create(MS))
// {
// XmlSerializer xmlSearializer = new XmlSerializer(typeof(CobraInput));
// InputData = (CobraInput)xmlSearializer.Deserialize(xr);
// InputResult = "Read XML Success";
// }
// }
// return InputResult;
//}
/ <summary>
/ 数据输出,序列化xml文本
/ </summary>
/ <returns></returns>
//public string FileOutput()
//{
// using (MemoryStream ms = new MemoryStream())
// {
// var setting = new XmlWriterSettings()
// {
// Encoding = new UTF8Encoding(false),
// Indent = true,
// };
// using (XmlWriter writer = XmlWriter.Create(ms, setting))
// {
// XmlSerializer xmlSearializer = new XmlSerializer(typeof(CobraOutput));
// xmlSearializer.Serialize(writer, OutputData);
// OutputXmlString = Encoding.UTF8.GetString(ms.ToArray());
// }
// }
// return OutputXmlString;
//}
}
}
https://www.cnblogs.com/guogangj/p/7489218.html斜体样式