zoukankan      html  css  js  c++  java
  • 在.NET2.0中解析Json和Xml

    在.NET解析json有很多方法,这里介绍最简单也用的最多的一种。

    一、添加引用

    解析Json,先下载开源控件 Newtonsoft.Json.dll

    下载地址:http://files.cnblogs.com/gosky/Newtonsoft.Json%E9%9B%86%E5%90%88.zip

    解压以后,在bin/Net20/中找到Newtonsoft.Json.dll复制到项目的bin目录下

    二、引用命名空间

    using Newtonsoft.Json.Linq;
    using Newtonsoft.Json;

    三、使用方法

    Json格式如下:jsonStr:{"errcode":40013,"errmsg":"invalid appid"}

    //创建JObject对象
    JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStr);
    string errcode = jo["errcode"].ToString();
    string errmsg = jo["errmsg"].ToString();

    四、解析xml

    在.NET2.0中解析XML需要使用的命名空间是:System.Xml;

    1.引用

    using System.Xml;

    2.解析

    要解析的xml如下:这里引用了微信接口中的文本消息报文格式。

    <xml>
    <ToUserName><![CDATA[gh_4c30545b3c2d]]></ToUserName>
    <FromUserName><![CDATA[o5cnujvIjKiGo4hgWiRCYtR73owM]]></FromUserName>
    <CreateTime>99999999</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[长江尚品]]></Content>
    <MsgId>1234567890123456</MsgId>
    </xml>

    解析语法:

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    //获取xml根节点 XmlNode root
    = doc.FirstChild;
    string ToUserName =  root.SelectSingleNode("ToUserName").InnerText;
    string FromUserName = root..SelectSingleNode("FromUserName").InnerText;
    ·········
    //解析方法同上

    也可以这样解析:

    //解析数据
    XmlDocument doc = new System.Xml.XmlDocument();
    doc.LoadXml(requestXml);
    XmlNode node = doc.SelectSingleNode("/xml/ToUserName");

    if (node != null){

      XmlCDataSection section = node.FirstChild as XmlCDataSection;
      if(section!=null){
        string ToUserName = section.Value;
      }
    }

    两种方法都可以。

  • 相关阅读:
    wx小程序用canvas生成图片流程与注意事项
    mysql导入导出csv
    机房测速
    python 后台服务
    python获取硬件信息模块
    nagios外部命令接口
    nginx下的nagios pnp4nagios
    supervisor运行virtualenv环境下的nagios-api
    check_mk通用应用检测插件
    pnp4nagios 性能调优
  • 原文地址:https://www.cnblogs.com/gosky/p/3474347.html
Copyright © 2011-2022 走看看