Sophie Huang
Time and tide wait for no man.

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>

 

posted on 2013-12-12 18:11  Sophie Huang  阅读(399)  评论(0编辑  收藏  举报