以下内容全部或部分转自或参考于网络。
完成以下内容需要安装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);
}
}