您的位置:首页 > 其它

Read XML file easily with LINQ to XML

2011-10-27 22:27 435 查看
/*By Jiangong SUN*/

How to read XML file easily?

1. You can get your stream with a given url.

private string GetStreamString(string url)
{
try
{
WebRequest request = WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
return streamRead.ReadToEnd();
}
catch (Exception e)
{
Log.Error(e);
return null;
}
}


2. Then get your XElement you want using LINQ to XML request:

private static IEnumerable<XElement> GetElements(string streamString, string matchName)
{
if (!string.IsNullOrEmpty(streamString))
{
XDocument xml = XDocument.Parse(streamString);

IEnumerable<XElement> d = (from x in xml.Root.Elements(matchName)
select x);
return d;
}
else
{
return null;
}
}


3. Then you can treat the data and use it your application.

A simple example:

RList = (from range in Ranges.Elements("node").Elements("subnode")
select range).ToList();


Enjoy coding!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: