WEB应用之解析XML格式数据

以下内容全部或部分转自或参考于网络。

完成以下内容需要安装Apache 服务,安装方法见“Apache(阿帕奇)Web服务器的安装和使用 ”。

在C:\Apache24\htdocs 目录中新建一个test.xml的文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<apps>
    <app>
    <id>1</id>
    <name>Google Maps</name>
    <version>1.0</version>
    </app>

    <app>
    <id>2</id>
    <name>Chrome</name>
    <version>2.1</version>
    </app>
</apps>

下面是XML文件操作示例:

        private void LoadXml()
        {
            //测试用,本网址为C:\Apache24\htdocs下的test.xml,使用模拟器时必须将localhost或127.0.0.1换成10.0.3.2(Genymotion 模拟器)
            string url = "http://10.0.3.2/test.xml" ;//"http://10.0.2.2/test.xml"(AVD 模拟器);
            try
            {
                //创建一个请求
                var httpReq = (HttpWebRequest )HttpWebRequest.Create( new Uri (url));
                httpReq.Method = "GET";
                httpReq.ContentType = "application/xml";
                //获取响应
                httpReq.BeginGetResponse( new AsyncCallback (ProcessRestXmlResponse), httpReq);
            }
            catch(WebException we)
            {
                tv.Text = "error: "+we.Message;
            }


        }

        private void ProcessRestXmlResponse(IAsyncResult ar)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest )ar.AsyncState;
                HttpWebResponse response;
                response = ( HttpWebResponse)request.EndGetResponse(ar);
                System.IO. StreamReader strm = new System.IO.StreamReader(response.GetResponseStream());
                System.Xml.Linq. XDocument xd = System.Xml.Linq.XDocument .Load(strm);
                System.Collections.Generic. List<XElement > list = new System.Collections.Generic.List <XElement>();
                //搜索xml文件的节点
                SearchElements(xd.Root, list);
                response.Close();

                RunOnUiThread(() => tv.Text = list[0].Value);
            }
            catch(System.Exception e)
            {
                RunOnUiThread(() => tv.Text = "error");
            }
        }

        public static void SearchElements( XElement ele, System.Collections.Generic.List <XElement> list)
        {
            //遍历ele的所有子节点
            foreach (XElement item in ele.Elements())
            {
                // 如果属性是"name"值是“Chrome”
                if (item.Name.LocalName == "name" )
                {
                    if (item.Value == "Chrome" )
                    {
                        list.Add(item.Parent);
                    }
                }

                // 如果item里面还有子节点就递归
                SearchElements(item, list);
            }
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值