public class WXMessage
{
public string ToUserName { get; set; }
public string FromUserName { get; set; }
public string CreateTime { get; set; }
public string MsgType { get; set; }
public string Content { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string PicUrl { get; set; }
public string MediaId { get; set; }
public string ThumbMediaId { get; set; }
public string Format { get; set; }
public string Location_X { get; set; }
public string Location_Y { get; set; }
public string Scale { get; set; }
public string Label { get; set; }
public string MsgId { get; set; }
public string AgentID { get; set; }
public string Recognition { get; set; }
public DateTime CRTime { get; set; }
}
简单解析XML :
public WXMessage DeserializeXML(string strXML)
{
TextReader txtReader = new StringReader(strXML);
XDocument xDocument = XDocument.Load(txtReader);
XElement xElement = xDocument.Element("xml").Element("MsgType");
WXMessage message = new WXMessage() ;
//反射填充信息
foreach (var xelement in xDocument.Element("xml").Elements())
{
message.GetType()
.GetProperties()
.Where(p => p.Name == xelement.Name.ToString().Trim())
.FirstOrDefault()
.SetValue(message, xelement.Value.ToString().Trim());
}
message.CRTime = DateTime.Now;
MessageTextInsert(message);
return message;
}
生成XML:
public string CreateTextXML(TextType textMessage)
{
XDocument xText = new XDocument(
new XElement("xml",
new XElement("ToUserName",textMessage.ToUserName),
new XElement("FromUserName",textMessage.FromUserName),
new XElement("CreateTime",textMessage.CreateTime),
new XElement("MsgType",textMessage.MsgType),
new XElement("Content",textMessage.Content)
)
);
string temp =xDocConvertToXmlString(xText);
return temp;
}
private string xDocConvertToXmlString(XDocument xdoc)
{
//处理CDATA转译问题
return xdoc.ToString().Replace("<", "<").Replace(">", ">");
}
网友评论