解析xml返回json

readxml.ashx中

返回json方法:

    function returnXmlJson(string xmlUrl)
    {
        //解析本地xml
        //XmlDocument xmldoc = new XmlDocument();
        //xmldoc.Load(xmlUrl);
        //解析远程xml文件
        WebClient wc = new WebClient();
        StreamReader sr = new StreamReader(wc.OpenRead(xmlUrl));//返回string流            
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(sr.ReadToEnd());
        XmlNode root = xmldoc.DocumentElement;//获取根节点news             
        XmlNodeList nodelist = root.ChildNodes;//items             
        string node1 = "";
        string node2 = "";
        string node3 = "";
        string node4 = "";
        xmlInfo xmlinfo = new xmlInfo();
        List<xmlInfo> xmlInfolist = new List<xmlInfo>();
        for (int i = 0; i < nodelist.Count; i++)
        {
            node1 = nodelist[i].ChildNodes[0].InnerText;//id                            
            node2 = nodelist[i].ChildNodes[1].InnerText;//title                    
            node3 = nodelist[i].ChildNodes[2].InnerText;//content                     
            node4 = nodelist[i].ChildNodes[3].InnerText;//pubdate              
            xmlinfo.id = node1;
            xmlinfo.title = node2;
            xmlinfo.content = node3;
            xmlinfo.pubdate = node4;
            xmlInfolist.Add(xmlinfo);
}
return JsonHelper.ObjectToJSON(xmlInfolist);//JsonHelper是一个json操作的类,此处调用它的对象转json的方法 }


xmlInfo类:

 class xmlInfo
    {
        public string id { get; set; }
        public string title { get; set; }
        public string content { get; set; }
        public string pubdate { get; set; }
    }


xml:

<?xml version="1.0" encoding="GBK" ?>
<news>
<item>
<title>this is title</title>
<content>this is content</content>
<date>2013-12-10 13:50:44</date>
</item>
<item>
<id>1</id>
<title>this is title</title>
<content>this is content</content>
<date>2013-12-10 13:50:44</date>
</item>
<item>
<id>2</id>
<title>this is title</title>
<content>this is content</content>
<date>2013-12-10 13:50:44</date>
</item>
<item>
<id>3</id>
<title>this is title</title>
<content>this is content</content>
<date>2013-12-10 13:50:44</date>
</item>
<item>
<id>4</id>
<title>this is title</title>
<content>this is content</content>
<date>2013-12-10 13:50:44</date>
</item>
</news>


前端读取json:

   <script type="text/javascript">
        $.getJSON(
            "http://localhost:12345/readxml.ashx",
            function (data) {
            var ids = "";
                for (var i = 0, n = data.length; i < n; i++) {
                    ids += data[i].id + "-----";
                }
                alert(ids);
            }
        );
    </script>

 

转载于:https://www.cnblogs.com/liuyueyingzi/p/3471758.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值