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!
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!
本文介绍了一种使用C#和LINQ to XML轻松读取XML文件的方法。通过提供的示例代码,您可以了解如何从给定URL获取XML流,并解析特定元素。
220

被折叠的 条评论
为什么被折叠?



