以读取博客园随笔备份为例 将xml 序列化成json,再序列化成对象
发布时间:2020-12-16 05:32:44 所属栏目:百科 来源:网络整理
导读:资源下载 :http://files.cnblogs.com/codealone/ConsoleApplication2.zip Json查看工具 :http://files.cnblogs.com/codealone/JsonView.zip 博客园随笔备份之后,得到的文件格式如下: 我们要读取上述xml,主要是获得channel节点下的所有内容,在平时的工作
资源下载:http://files.cnblogs.com/codealone/ConsoleApplication2.zip Json查看工具:http://files.cnblogs.com/codealone/JsonView.zip 博客园随笔备份之后,得到的文件格式如下:
我们要读取上述xml,主要是获得channel节点下的所有内容,在平时的工作过程中,觉得json数据要比xml更加容易操作些,于是想,能不能将其转换成json格式,进一步转换成对象。下一步的工作则是将 rss节点下的内容,转换为json。 主要代码如下: var xml = File.ReadAllText(@"D:cnblogs.xml");//该xml为博客园随笔备份文件 XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); 获取rss节点下的内容 var channelXml = doc.SelectSingleNode("rss").InnerXml; 进一步细化xml格式,内容仅为rss节点下的内容 doc.LoadXml(channelXml); 将xml序列化成json,并且去掉根节点 var json = JsonConvert.SerializeXmlNode(doc,Newtonsoft.Json.Formatting.None,true);
此时json的内容如下: 此时由xml到json的转换就完成了,下一步,则是如何将json转换成对象。通过查看上述json的结构,将每个节点看作一个对象,很容易定义出数据结构,具体如下: public class Channel { string title { get; set; } string link { string description { string language { string lastBuildDate{ string pubDate { string ttl { public List<Channel_Item> item { ; } } Channel_Item { string author { string guid { public Item_Description description { Item_Description { 默认以变量名称作为json序列化的节点,由于该节点内容不符合变量定义规范,则显示指定即可 [JsonProperty(#cdata-section)] string content { ; } } |