对象生成自定义节点的XML
public static string CreateXmlFile<T>(T Object, string InterfaceName, string code, string message)
{
XmlDocument xmlDoc = new XmlDocument();
//创建类型声明节点
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");//自定义xml编码格式
xmlDoc.AppendChild(node);
//创建节点
XmlNode root1 = xmlDoc.CreateElement("data");
XmlNode root2 = xmlDoc.CreateElement("message");
XmlNode root3 = xmlDoc.CreateElement("record");
//节点添加属性值
XmlElement re1 = (XmlElement)root1;
re1.SetAttribute("name", InterfaceName);//提交的接口名
re1.SetAttribute("code", code);//返回的状态码,0为失败,1为成功
XmlElement re2 = (XmlElement)root2;
re2.SetAttribute("message", message);//响应消息的内容
//取对象属性
if (Object != null)
{
XmlElement re3 = (XmlElement)root3;
Type type = Object.GetType();//获取对象的类型
foreach (System.Reflection.PropertyInfo p in type.GetProperties())
{
string o = GetPropertyValue(Object, p.Name) == null ? "" : GetPropertyValue(Object, p.Name).ToString();
re3.SetAttribute(p.Name, o);
}
}
xmlDoc.AppendChild(root1);//根节点绑定
root1.AppendChild(root2);//子节点绑定
root1.AppendChild(root3);//子节点绑定
return xmlDoc.InnerXml.ToString();
}
public static object GetPropertyValue(object info, string field)
{
if (info == null) return null;
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
return property.First().GetValue(info, null);
}
取自定义节点的xml对象的某个节点属性值转换成对象
public static T AnalysisXmlToObj<T>(string xml) where T : class, new()
{
T t = new T();//实例化对象,以便取出对象所有属性
// 获得此模型的公共属性
List<KValue> list = new List<KValue>();//存放节点中属性名和属性值
var doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode node = doc.SelectSingleNode("//record");//取xml中的record节点
for (int i = 0; i < node.Attributes.Count; i++)
{
var s = node.Attributes;
KValue kv = new KValue()
{
key = node.Attributes[i].Name,//节点属性名
value = node.Attributes[i].Value == "" ? null : node.Attributes[i].Value//节点属性值
};
list.Add(kv);
}
for (int i = 0; i < list.Count; i++)
{
//根据属性名获得指定的属性对象
PropertyInfo gc = t.GetType().GetProperty(list[i].key);//从对象中查询xml中存在的对象属性
gc.SetValue(t, Convert.ChangeType(list[i].value, gc.PropertyType), null);//给对象属性赋值
}
return t;
}
public class KValue
{
public string key { get; set; }
public string value { get; set; }
}
重点*****:泛型T在方法中需要实例化,则必须在方法后面加上where T:class new();否则实例化不成功。