Reading and querying XML file in C#
Reading and querying XML data is good with Link to XML in C#. LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework.
Documentation and examples of how to use it are published at LINQ to XML (C#), but in this post I post down useful for me snippets.
First variable is a filepath.
string filepath = @"c:\users\documents\visual studio 2013\Projects\MyXMLReader\ readxml\listfeed.xml";
1. Read and query Read via XDocument
In case of XDocument you load all the nodes of XML-file. To get the top-level node you should use Root. You can add where clause according to values of neighborhood elements.
var xml = XDocument.Load(filepath, LoadOptions.None); Console.WriteLine(DateTime. Today); var query = from c in xml.Root.Descendants("item") where (DateTime)c.Element("pubDate") > DateTime.Parse("17.07.2017 0:00:00") select c; foreach (XElement title in query) { Console.WriteLine(title. Element("pubDate").Value + " : " + title.Element("title").Value); }
2. Read and query XML via XElement
In case of reading via XElement you can get non-root nodes. You may apply filters only to attribute values.
XElement xelm = XElement.Load(filepath); IEnumerable<XElement> ititles = from el in xelm.Elements() select el; foreach (XElement tt in ititles) { Console.WriteLine(tt.Element(" pubDate").Value + " : " + tt.Element("title").Value); }