c# 4.0 - Parsing Elements in Second Nesting Level of XML File -
i working on little executable application. application xml parser parse xml file , store data parsed database. xml file application magic on has following structure:
<?xml version="1.0" encoding="utf-8"?> <events> <event> <book>felicity fly</book> <author>christina gabbitas</author> <bookimgurl>http://www.whsmith.co.uk/images/products\957\255\9780957255203_t_f.jpg</bookimgurl> <info>christina gabbitas signing copies of new book, felicity fly. books should bought whsmith. proof of purchase may necessary</info> <date>25 may 2013</date> <starttime>10:30</starttime> <location> <name>whsmith brent cross</name> <address>brent cross shopping centre</address> <city>london</city> <county/> <postcode>nw4 3fb</postcode> <tel>020 8202 4226</tel> </location> </event> <!-- many more events above here --> </events> and here have far in terms of code parsing logic.
namespace xmlparser { public class parser { static void main(string[] args) { var path_to_xml = "data.xml"; var xdoc = xdocument.load(path_to_xml); var events = e in xdoc.descendants("event") select new { book = (string)e.element("book").value, author = (string)e.element("author").value, bookimgurl = (string)e.element("bookimgurl").value, info = (string)e.element("info").value, date = (string)e.element("date").value, time = (string)e.element("starttime").value, // stuck here } } } } i stuck location node, don't know how parse location related information.
any appreciated.
thank you.
you have decide whether you're using (string)xelement casting or xelement.value property.
(string)e.element("book").value compiles , works fine, xelement.value string, casting string pointless. suggest using (string)xelement, because won't cause nullreferenceexception when element won't find.
you can use let keyword e.element("location") once, , use location-related values:
var xdoc = xdocument.parse(xml); var events = e in xdoc.descendants("event") let l = e.element("location") select new { book = (string)e.element("book"), author = (string)e.element("author"), bookimgurl = (string)e.element("bookimgurl"), info = (string)e.element("info"), date = (string)e.element("date"), time = (string)e.element("starttime"), location = new { name = (string)l.element("name"), address = (string)l.element("address"), city = (string)l.element("city"), county = (string)l.element("county"), postcode = (string)l.element("postcode"), tel = (string)l.element("tel") } }; console.writeline(events.first().location.city);
Comments
Post a Comment