C#_XML与Object转换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization; namespace Utility
{
public class XMLHelper
{
#region object --> XML string.
public static string ToRequestXML<T>(T obj) where T : class
{
string xmlStr = string.Empty;
try
{
var type = typeof(T);
var properties = type.GetProperties();
XmlDocument xd = new XmlDocument();
XmlElement xe = xd.CreateElement("msgBody"); for (int i = ; i < properties.Length; i++)
{
var elementName = properties[i].Name; #region current type is List
if (properties[i].PropertyType.FullName.Contains("System.Collections.Generic.List"))
{
var propertyValue = properties[i].GetValue(obj, null);
if (propertyValue == null)
{
XmlElement xa = xd.CreateElement(elementName);
xe.AppendChild(xa);
}
else
{
xe = getArray(propertyValue, xe, xd, true, true, elementName);
}
continue;
}
#endregion #region current type is Array
if (properties[i].PropertyType.BaseType.Name == "Array")
{
var propertyName = properties[i].Name;
var propertyValue = properties[i].GetValue(obj, null);
if (propertyValue == null)
{
XmlElement xa = xd.CreateElement(elementName);
xe.AppendChild(xa);
}
else
{
xe = getArray(propertyValue, xe, xd, true, false, elementName);
}
continue;
}
#endregion #region current type is Model
if (properties[i].PropertyType.BaseType.Name != "Array" && (properties[i].PropertyType != typeof(long) && properties[i].PropertyType != typeof(int) && properties[i].PropertyType != typeof(string)) && !properties[i].PropertyType.FullName.Contains("System.Collections.Generic.List"))
{
var childPropertyName = properties[i].Name;
var childPropertyValue = properties[i].GetValue(obj, null); if (childPropertyValue == null)
{
var modelType = properties[i].PropertyType.UnderlyingSystemType;
var model = modelType.Assembly.CreateInstance(modelType.FullName);
xe = getArray(model, xe, xd, false, false, elementName);
}
else
{
xe = getArray(childPropertyValue, xe, xd, false, false, elementName);
}
continue;
}
#endregion #region current type is int or string
if (properties[i].PropertyType == typeof(long) || properties[i].PropertyType == typeof(string) || properties[i].PropertyType == typeof(int))
{
var childPropertyName = properties[i].Name;
var childPropertyValue = properties[i].GetValue(obj, null);
XmlElement xa = xd.CreateElement(childPropertyName);
if (childPropertyValue != null)
{
xa.InnerText = childPropertyValue.ToString();
}
else
{
xa.InnerText = "";
}
xe.AppendChild(xa);
continue;
}
#endregion
}
xd.AppendChild(xe);
xmlStr = xd.InnerXml;
return xmlStr;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region Get array value
private static XmlElement getArray(object propertyValue, XmlElement xe, XmlDocument xd, bool isArray, bool isList , string elementName)
{
try
{
if (propertyValue != null)
{
if (isList)
{
#region current type is Array
var array = propertyValue as System.Collections.IEnumerable;
if (array != null)
{
foreach (var item in array)
{
var obj = item;
var type = item.GetType();
var properties = type.GetProperties();
XmlElement childXe = xd.CreateElement(elementName);
for (int i = ; i < properties.Length; i++)
{
var propertyType = properties[i].PropertyType; #region current type is List
if (properties[i].PropertyType.FullName.Contains("System.Collections.Generic.List"))
{
var elementName2 = properties[i].Name;
var propertyValue2 = properties[i].GetValue(obj, null);
if (propertyValue2 == null)
{
XmlElement xa = xd.CreateElement(elementName);
childXe.AppendChild(xa);
}
else
{
childXe = getArray(propertyValue2, childXe, xd, true, true, elementName2);
}
continue;
}
#endregion #region current type is Array
if (properties[i].PropertyType.BaseType.Name == "Array")
{
var elementName2 = properties[i].Name;
var childPropertyValue = properties[i].GetValue(obj, null);
if (childPropertyValue == null)
{
XmlElement xa = xd.CreateElement(elementName);
childXe.AppendChild(xa);
}
else
{
childXe = getArray(childPropertyValue, childXe, xd, true, false, elementName2);
} }
#endregion #region current type is Model
if (properties[i].PropertyType.BaseType.Name != "Array" && (properties[i].PropertyType != typeof(long) && properties[i].PropertyType != typeof(int) && properties[i].PropertyType != typeof(string)) && !properties[i].PropertyType.FullName.Contains("System.Collections.Generic.List"))
{
elementName = properties[i].Name;
var childPropertyValue = properties[i].GetValue(obj, null);
if (childPropertyValue == null)
{
var modelType = type.UnderlyingSystemType;
var model = modelType.Assembly.CreateInstance(modelType.FullName);
xe = getArray(model, xe, xd, false, false, elementName);
}
else
{
childXe = getArray(childPropertyValue, childXe, xd, false, false, elementName);
}
}
#endregion #region current type is Number
if (properties[i].PropertyType == typeof(long) || properties[i].PropertyType == typeof(string) || properties[i].PropertyType == typeof(int))
{
var childPropertyName = properties[i].Name;
var childPropertyValue = properties[i].GetValue(obj, null);
XmlElement xa = xd.CreateElement(childPropertyName);
if (childPropertyValue != null)
{
xa.InnerText = childPropertyValue.ToString();
}
else
{
xa.InnerText = "";
}
childXe.AppendChild(xa);
}
#endregion
}
xe.AppendChild(childXe);
}
}
else
{
var list = (List<object>)propertyValue;
}
#endregion
return xe;
} if (isArray)
{
#region current type is Array
var array = (Array)propertyValue;
if (array != null)
{
for (int i = ; i < array.Length; i++)
{
var obj = array.GetValue(i);
var type = array.GetValue(i).GetType();
var properties = type.GetProperties();
XmlElement childXe = xd.CreateElement(elementName);
for (int j = ; j < properties.Length; j++)
{
var propertyType = properties[j].PropertyType; #region current type is List
if (properties[j].PropertyType.FullName.Contains("System.Collections.Generic.List"))
{
var elementName2 = properties[j].Name;
var propertyValue2 = properties[j].GetValue(obj, null);
if (propertyValue2 == null)
{
XmlElement xa = xd.CreateElement(elementName);
childXe.AppendChild(xa);
}
else
{
childXe = getArray(propertyValue2, childXe, xd, true, true, elementName2);
}
continue;
}
#endregion #region current type is Array
if (properties[j].PropertyType.BaseType.Name == "Array")
{
var elementName2 = properties[j].Name;
var childPropertyValue = properties[j].GetValue(obj, null);
if (childPropertyValue == null)
{
XmlElement xa = xd.CreateElement(elementName);
childXe.AppendChild(xa);
}
else
{
childXe = getArray(childPropertyValue, childXe, xd, true, false, elementName2);
} }
#endregion #region current type is Model
if (properties[j].PropertyType.BaseType.Name != "Array" && (properties[j].PropertyType != typeof(long) && properties[j].PropertyType != typeof(int) && properties[j].PropertyType != typeof(string)))
{
elementName = properties[j].Name;
var childPropertyValue = properties[j].GetValue(obj, null);
if (childPropertyValue == null)
{
var modelType = properties[i].PropertyType.UnderlyingSystemType;
var model = modelType.Assembly.CreateInstance(modelType.FullName);
xe = getArray(model, xe, xd, false, false, elementName);
}
else
{
childXe = getArray(childPropertyValue, childXe, xd, false, false, elementName);
}
}
#endregion #region current type is Number
if (properties[j].PropertyType == typeof(long) || properties[j].PropertyType == typeof(string) || properties[j].PropertyType == typeof(int))
{
var childPropertyName = properties[j].Name;
var childPropertyValue = properties[j].GetValue(obj, null);
XmlElement xa = xd.CreateElement(childPropertyName);
if (childPropertyValue != null)
{
xa.InnerText = childPropertyValue.ToString();
}
else
{
xa.InnerText = "";
}
childXe.AppendChild(xa);
}
#endregion
}
xe.AppendChild(childXe);
}
}
else
{
var list = (List<object>)propertyValue;
}
#endregion
}
else
{
#region current type isn't Array
var objType = propertyValue.GetType();
var properties = objType.GetProperties();
XmlElement childXe = xd.CreateElement(elementName);
for (int j = ; j < properties.Length; j++)
{
var propertyType = properties[j].PropertyType; #region current type is Array
if (properties[j].PropertyType.BaseType.Name == "Array")
{
var elementName2 = properties[j].Name;
var childPropertyValue = properties[j].GetValue(propertyValue, null);
if (childPropertyValue == null)
{
XmlElement xa = xd.CreateElement(elementName);
childXe.AppendChild(xa);
}
else
{
childXe = getArray(childPropertyValue, childXe, xd, true, false, elementName2);
}
}
#endregion #region current type is Model
if (properties[j].PropertyType.BaseType.Name != "Array" && (properties[j].PropertyType != typeof(long) && properties[j].PropertyType != typeof(int) && properties[j].PropertyType != typeof(string)))
{
elementName = properties[j].Name;
var childPropertyValue = properties[j].GetValue(propertyValue, null);
if (childPropertyValue == null)
{
var modelType = properties[j].PropertyType.UnderlyingSystemType;
var model = modelType.Assembly.CreateInstance(modelType.FullName);
xe = getArray(model, xe, xd, false, false, elementName);
}
else
{
childXe = getArray(childPropertyValue, childXe, xd, false, false, elementName);
}
}
#endregion #region current is Number
if (properties[j].PropertyType == typeof(long) || properties[j].PropertyType == typeof(string) || properties[j].PropertyType == typeof(int))
{
var childPropertyName = properties[j].Name;
var childPropertyValue = properties[j].GetValue(propertyValue, null);
XmlElement xa = xd.CreateElement(childPropertyName);
if (childPropertyValue != null)
{
xa.InnerText = childPropertyValue.ToString();
}
else
{
xa.InnerText = "";
}
childXe.AppendChild(xa);
}
#endregion
}
xe.AppendChild(childXe);
#endregion
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return xe;
}
#endregion #region XML string --> object
/// <summary>
/// Convert xml message to object
/// </summary>
/// <param name="type"></param>
/// <param name="xmlStr"></param>
/// <returns></returns>
public static T ToResponseObject<T>(string xmlStr) where T : new()
{
try
{
//T obj = default(T);
T obj = new T();
var repType = typeof(T);
XmlDocument document = new XmlDocument();
document.LoadXml(xmlStr); //加载Xml文件
XmlElement node = document.DocumentElement; //xml的根标签
var nodeList = document.ChildNodes;
var properties = repType.GetProperties(); foreach (var itemProp in properties)
{
#region current type is List
if (itemProp.PropertyType.FullName.Contains("System.Collections.Generic.List"))
{ object array = new object();
var arryLength = ;
var notNullLength = ;
var arryType = itemProp.PropertyType.UnderlyingSystemType; var objList = itemProp.GetValue(obj, null) as System.Collections.IEnumerable;
var enumt = objList.GetEnumerator();
//enumt.
var currentType = itemProp.PropertyType.GetGenericArguments()[]; foreach (XmlNode xmlitem in node.ChildNodes)
{
if (xmlitem.Name == itemProp.Name)
{
arryLength++;
}
}
if (arryLength > )
{
var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
foreach (XmlNode item in node.ChildNodes)
{
//current type is array
if (item.Name == itemProp.Name)
{
var model = currentType.Assembly.CreateInstance(currentType.FullName); // arryType.GetElementType().Assembly.CreateInstance(currentType.FullName);
SetArray(item.ChildNodes, model,true);
arrayModel.Add(model);
//arrayModel[notNullLength] = model;
notNullLength++;
}
}
itemProp.SetValue(obj, arrayModel, null);
} continue;
}
#endregion var baseType = itemProp.PropertyType.BaseType.Name;
if (baseType == "Array")
{
#region Current type is Array
object array = new object();
var arryLength = ;
var notNullLength = ;
var arryType = itemProp.PropertyType.UnderlyingSystemType;
foreach (XmlNode xmlitem in node.ChildNodes)
{
if (xmlitem.Name == itemProp.Name)
{
arryLength++;
}
}
if (arryLength > )
{
var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
foreach (XmlNode item in node.ChildNodes)
{
//current type is array
if (item.Name == itemProp.Name)
{
var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName);
SetArray(item.ChildNodes, model);
arrayModel[notNullLength] = model;
notNullLength++;
}
}
itemProp.SetValue(obj, arrayModel, null);
}
#endregion continue;
}
else
{
#region Current type isn't Array
foreach (XmlNode item in node.ChildNodes)
{
#region Current type is Number
if (itemProp.Name == item.Name && (itemProp.PropertyType == typeof(long) || itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(string)))
{
if (itemProp.PropertyType == typeof(int) || itemProp.PropertyType == typeof(long))
{
if (!string.IsNullOrEmpty(item.InnerText))
{
if (itemProp.PropertyType == typeof(int))
{
itemProp.SetValue(obj, Convert.ToInt32(item.InnerText), null);
}
else
{
itemProp.SetValue(obj, Convert.ToInt64(item.InnerText), null);
} }
else
{
itemProp.SetValue(obj, , null);
}
}
else
{
itemProp.SetValue(obj, item.InnerText, null);
}
}
#endregion #region Current type is Model
if (itemProp.PropertyType != typeof(long) && itemProp.PropertyType != typeof(string) && itemProp.PropertyType != typeof(int) && itemProp.PropertyType.Name == item.Name && item.HasChildNodes && item.FirstChild.NodeType == System.Xml.XmlNodeType.Element)
{
var modelType = itemProp.PropertyType.UnderlyingSystemType;
var model = modelType.Assembly.CreateInstance(modelType.FullName);
SetArray(item.ChildNodes, model);
itemProp.SetValue(obj, model, null);
}
#endregion
}
#endregion continue;
}
}
repType = obj.GetType();
return obj;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion #region Set array value
private static Object SetArray(XmlNodeList xmlNodeList, object obj,bool isList = false)
{
try
{
var type = obj.GetType();
var properties = type.GetProperties();
foreach (var itemProp in properties)
{
//if (isList)
if (itemProp.PropertyType.FullName.Contains("System.Collections.Generic.List"))
{
#region Current type is List
object array = new object();
var arryLength = ;
var notNullLength = ;
var arryType = itemProp.PropertyType.UnderlyingSystemType;
var currentType = itemProp.PropertyType.GetGenericArguments()[];
foreach (XmlNode xmlitem in xmlNodeList)
{
if (xmlitem.Name == itemProp.Name)
{
arryLength++;
}
} if (arryLength > )
{
var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
foreach (XmlNode item in xmlNodeList)
{
//current type is array
if (item.Name == itemProp.Name)
{
var model = currentType.Assembly.CreateInstance(currentType.FullName); // var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName);
SetArray(item.ChildNodes, model,true);
arrayModel.Add(model);
notNullLength++; }
}
itemProp.SetValue(obj, arrayModel, null);
}
#endregion
return obj;
} var baseType = itemProp.PropertyType.BaseType.Name;
if (baseType == "Array")
{
#region Current type is Array
object array = new object();
var arryLength = ;
var notNullLength = ;
var arryType = itemProp.PropertyType.UnderlyingSystemType;
foreach (XmlNode xmlitem in xmlNodeList)
{
if (xmlitem.Name == itemProp.Name)
{
arryLength++;
}
} if (arryLength > )
{
var arrayModel = arryType.InvokeMember("Set", System.Reflection.BindingFlags.CreateInstance, null, array, new object[] { arryLength }) as System.Collections.IList;
foreach (XmlNode item in xmlNodeList)
{
//current type is array
if (item.Name == itemProp.Name)
{
var model = arryType.GetElementType().Assembly.CreateInstance(arryType.GetElementType().FullName);
SetArray(item.ChildNodes, model);
arrayModel[notNullLength] = model;
notNullLength++; }
}
itemProp.SetValue(obj, arrayModel, null);
}
#endregion
}
else
{
foreach (XmlNode item in xmlNodeList)
{
#region Current type is Number
if (itemProp.Name == item.Name && (itemProp.PropertyType == typeof(long) || itemProp.PropertyType == typeof(int) || itemProp.PropertyType ==typeof(string)))
{
if (itemProp.PropertyType== typeof(int) || itemProp.PropertyType== typeof(long))
{
if (!string.IsNullOrEmpty(item.InnerText))
{
if (itemProp.PropertyType == typeof(int))
{
itemProp.SetValue(obj, Convert.ToInt32(item.InnerText), null);
}
else
{
itemProp.SetValue(obj, Convert.ToInt64(item.InnerText), null);
}
}
else
{
itemProp.SetValue(obj, , null);
}
}
else
{
itemProp.SetValue(obj, item.InnerText, null);
}
}
#endregion #region Current type is Model
if (itemProp.PropertyType != typeof(long) && itemProp.PropertyType != typeof(int) && itemProp.PropertyType != typeof(string) && itemProp.PropertyType.Name == item.Name && item.HasChildNodes && item.FirstChild.NodeType == System.Xml.XmlNodeType.Element)
{
var modelType = itemProp.PropertyType.UnderlyingSystemType;
var model = modelType.Assembly.CreateInstance(modelType.FullName);
SetArray(item.ChildNodes, model);
itemProp.SetValue(obj, model, null);
}
#endregion
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return obj;
}
#endregion
} public class XMLNew
{
public static void ToXML()
{
try
{
TestA testA = new TestA();
List<TestC> testCList = new List<TestC>();
List<TestB> testBList = new List<TestB>();
List<TestD> testDList = new List<TestD>(); TestB testB = new TestB();
TestC testC = new TestC();
TestD testD = new TestD(); testCList.Add(testC);
testCList.Add(testC);
testBList.Add(testB);
testBList.Add(testB);
testDList.Add(testD);
testDList.Add(testD); testC.TestDArray = testDList.ToArray();
//testC.TestDList = testDList; //testB.TestCList = testCList;
testB.TestCArray = testCList.ToArray(); testA.TestBArray = testBList.ToArray();
//testA.TestBList = testBList; //string rqstXmlBody = Server.DataAccess.CallServerHelper.ToRequestXML<TestA>(testA);
string xml = Utility.XMLHelper.ToRequestXML<TestA>(testA); var obj = Utility.XMLHelper.ToResponseObject<TestA>(xml);
//var obj2 = Server.DataAccess.CallServerHelper.ToResponseObject<TestA>(rqstXmlBody);
}
catch (Exception ex)
{
//MessageHelper.Error(ex.Message);
}
}
} [Serializable]
public class TestD
{
public TestD()
{
D1 = "D1";
D2 = "D2";
}
public string D1 { get; set; }
public string D2 { get; set; }
} [Serializable]
public class TestC
{
public TestC()
{
C1 = "C1";
C2 = "C2";
}
public string C1 { get; set; }
public string C2 { get; set; } public TestD[] TestDArray { get; set; }
//public List<TestD> TestDList { get; set; }
} [Serializable]
public class TestB
{
public TestB()
{
//TestCList = new List<TestC>();
B1 = "B1";
B2 = "B2";
} public string B1 { get; set; }
public string B2 { get; set; } public TestC[] TestCArray { get; set; }
//public List<TestC> TestCList { get; set; }
} [Serializable]
public class TestA
{
public string A1 { get; set; }
public string A2 { get; set; }
public TestA()
{
//TestBList = new List<TestB>();
A1 = "A1";
A2 = "A2";
}
public TestB[] TestBArray { get; set; }
//public List<TestB> TestBList { get; set; }
} }
C#_XML与Object转换的更多相关文章
- 用于把List<Object>转换成Map<String,Object>形式
/** * 用于把List<Object>转换成Map<String,Object>形式,便于存入缓存 * @author zhang_bo * @param keyName ...
- java Object转换成指定的类型
java Object转换成指定的类型 /** * Object转成指定的类型 * @param obj * @param type * @param <T> * @return */ p ...
- LINQ系列:Linq to Object转换操作符
转换是指将输入对象的类型转变为序列的动作. 1. AsEnumerable AsEnumerable操作符将查询的输入以IEnumberable(T)类型返回. 2. Cast Cast操作符将IEn ...
- C#如何把List of Object转换成List of T具体类型
上周码程序的时候碰到个问题,因为设计上的约束,一个方法接受的参数只能为List<object>类型,然而该方法需要处理的真实数据则是确定的List<Currency>.然而C# ...
- 匿名类型和Object转换
本文转载:http://www.cnblogs.com/JustRun1983/archive/2012/05/13/2497997.html net中的匿名类型非常好用, 但是开发中遇到一个问题,当 ...
- java中Object转换成int或String类型方法
转载: http://www.cnblogs.com/1020182600HENG/p/6137206.html Object obj = getObject(); if(obj instanceof ...
- 将Object转换成Dictionary方法
如果Object是Dictionary类型,直接返回 如果Object是NameValueCollection类型,则添加到Dictionary里 如果Object是Hashtable类型,添加到Di ...
- 将[object Object]转换成json对象
这两天在做中英文双版的文件,页面根据语言读取不同的内容.js模板用的是ejs json文件: "components":{ "pages":{ "ho ...
- 将object转换成dyamic类型 解决long输出到浏览器过长精度丢失问题
需求: 数据库使用飘雪算法保存唯一标识 是一个18位长整形 将数据输出到浏览器时出现了精度丢失问题,这是一个重大的BUG.如果没解决好整个项目都要改一遍. 讨论有三个办法 1.把所有实体 数据模型的 ...
随机推荐
- 高德地图JS API 开发小结
项目中有一块功能要用到高德地图,所以,想把编码小结一下. 首先是地图的初始化 var map = new AMap.Map("mapDiv", { ...
- Logstash收集nginx访问日志和错误日志
1.收集访问日志 1).首先是要在nginx里面配置日志格式化输出 log_format main "$http_x_forwarded_for | $time_local | $reque ...
- January 04th, 2018 Week 01st Thursday
Just do what works for you, because there will always be someone who think differently. 就做你自己所能做的,因为 ...
- 模糊查询sql语句条件是中文在后台从数据库查不到结果,是英文和字母就可以,而且统一编码为UTF-8了!!!
4.在mysql安装目录下打开my.ini文件 5.保存,接着打开电脑的服务选项,将MySQL 重启 6. 重启后重新进入dos 窗口的MySQL ,输入show variables like &qu ...
- [Jenkins] 如何修改jenkins上的环境变量
现象 当本地的环境变量发生变化时,在jenkins 构建时里面访问的环境变量仍是之前旧的(未更新的)导致构建出现错误,比如我以我所遇到的问题进行简单写下,下面例子中我是涉及到修改 PYTHONPATH ...
- 用Promise解决多个异步Ajax请求导致的代码嵌套问题【转】
问题 前端小同学在做页面的时候,犯了个常见的错误:把多个Ajax请求顺序着写下来了,而后面的请求,对前面请求的返回结果,是有依赖的.如下面的代码所示: var someData; $.ajax({ u ...
- luogu P2860 [USACO06JAN]冗余路径Redundant Paths
题目描述 In order to get from one of the F (1 <= F <= 5,000) grazing fields (which are numbered 1- ...
- css3 媒体查询常用适配
@media (max-width:1300px) {} @media (max-width:1080px) {} @media (max-width:799px) {} @media (max-wi ...
- 修改sqlserver的数据库名、物理名称和逻辑文件名
作者:dym0080 来源:CSDN 原文:https://blog.csdn.net/dym0080/article/details/81017777 版权声明:本文为博主原创文章,转载请附上博文链 ...
- python在图片上写汉字
1.python opencv的putText只能画英文上去 2.借鉴这个https://blog.csdn.net/dcrmg/article/details/79108491 使用pil 首先,你 ...