读xml内容
XmlDocument xml = new XmlDocument();
xml.LoadXml(ret);
XmlNode NODE = xml.SelectSingleNode(“//Ex_Message//Ex_DevIp”);
if (NODE == null)
{
throw new Exception("报文格式错误,不存在XML节点:");
}
写xml内容
XmlDocument xmlDoc = new XmlDocument();
//描述
XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xmlDoc.AppendChild(xmlDec);
//根节点
XmlNode rootNode = xmlDoc.CreateElement("Ex_Message");
xmlDoc.AppendChild(rootNode);
//报文头
string DTNow = DateTime.Now.ToString("yyyyMMddHHmmss");
XmlNode node = xmlDoc.CreateElement("Ex_TrTime");
node.InnerText = DTNow;
rootNode.AppendChild(node);
string ret = xmlDoc.InnerXml;//得到xml字符串
xml内容转成实体类的通用函数,要求xml节点名和实体类属性名称一致:
public static List<T> GetInnerTexts<T>(XmlDocument xml, string Xpath) where T : new()
{
XmlNodeList NODES = xml.SelectNodes(Xpath);
if (NODES == null)
{
throw new Exception("报文格式错误,不存在XML节点:" + Xpath);
}
List<T> objs = new List<T>();
T obj;
Type type = typeof(T);//obj.GetType();
//遍历循环节点内容
foreach (XmlElement ele in NODES)
{
obj = new T();
//遍历所有属性名称,取出对应XML里的值。进行赋值
foreach (var prop in type.GetProperties())
{
if (prop.CanWrite)//判断属性可写,过滤只读属性
prop.SetValue(obj, ele.GetElementsByTagName(prop.Name)[0].InnerText, null);
}
objs.Add(obj);
}
return objs;
}