XML 和 List 互转类

XML 和 List 互转类


usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Xml;

namespaceXmlHelper
{
/// <summary>
实体转Xml,Xml转实体类
</summary> <typeparamname="T"></typeparam>
public classXmlHelper<T> whereT: new()
{
#region实体类转成Xml
对象实例转成xml
<paramname="item"> 对象实例 </param> <returns></returns> static stringEntityToXml(Titem)
{
IList<T>items= newList<T>();
items.Add(item);
returnEntityToXml(items);
}

对象实例集转成xml
<paramname="items"> 对象实例集 stringEntityToXml(IList<T>items)
{
// 创建XMLDocument文档
XmlDocumentdoc= newXmlDocument();
创建根元素
XmlElementroot=doc.CreateElement( typeof(T).Name+ " s ");
添加根元素的子元素集
foreach(Titem initems)
{
EntityToXml(doc,root,item);
}
向XmlDocument文档添加根元素
doc.AppendChild(root);

returndoc.InnerXml;
}

private voidEntityToXml(XmlDocumentdoc,XmlElementroot,Titem)
{
创建元素
XmlElementxmlItem=doc.CreateElement( typeof(T).Name);
对象的属性

System.Reflection.PropertyInfo[]propertyInfo=
typeof(T).GetProperties(System.Reflection.BindingFlags.Public|
System.Reflection.BindingFlags.Instance);



foreach(System.Reflection.PropertyInfopinfo inpropertyInfo)
{
if(pinfo!= null)
{
对象属性名称 stringname=pinfo.Name;
对象属性 stringvalue=String.Empty;

if(pinfo.GetValue(item,null)!= null)
value=pinfo.GetValue(item,255)">null).ToString(); 获取对象属性
设置元素的属性
xmlItem.SetAttribute(name,value);
}
}
向根添加子元素
root.AppendChild(xmlItem);
}


#endregion

#regionXml转成实体类

Xml转成对象实例
<paramname="xml"> xml staticTXmlToEntity( stringxml)
{
IList<T>items=XmlToEntityList(xml);
if(items!= null&&items.Count> 0)
returnitems[ 0];
else return default(T);
}

Xml转成对象实例集
staticIList<T>XmlToEntityList( stringxml)
{
XmlDocumentdoc= try
{
doc.LoadXml(xml);
}
catch
{
null;
}
if(doc.ChildNodes.Count!= 1)
null;
if(doc.ChildNodes[ 0].Name.ToLower()!= typeof(T).Name.ToLower()+ ")
null;

XmlNodenode=doc.ChildNodes[ 0];

IList<T>items= newList<T>();

foreach(XmlNodechild innode.ChildNodes)
{
if(child.Name.ToLower()== typeof(T).Name.ToLower())
items.Add(XmlNodetoEntity(child));
}

returnitems;
}

staticTXmlNodetoEntity(XmlNodenode)
{
Titem= newT();

if(node.NodeType==XmlNodeType.Element)
{
XmlElementelement=(XmlElement)node;

System.Reflection.PropertyInfo[]propertyInfo=
typeof(T).GetProperties(System.Reflection.BindingFlags.Public|
System.Reflection.BindingFlags.Instance);

foreach(XmlAttributeattr inelement.Attributes)
{
stringattrName=attr.Name.ToLower();
stringattrValue=attr.Value.ToString();
stringname=pinfo.Name.ToLower();
TypedbType=pinfo.PropertyType;
if(name==attrName)
{
if(String.IsNullOrEmpty(attrValue))
continue;
switch(dbType.ToString())
{
case system.int32 ":
pinfo.SetValue(item,Convert.ToInt32(attrValue),255)">null);
break;
System.Boolean System.DateTime System.Decimal System.Double default:
pinfo.SetValue(item,attrValue,255)">break;
}
continue;
}
}
}
}
}
returnitem;
}

#endregion
}

}

XML转List

List转XML

Model转XML

XML转Model

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念