How can I use Linq to build a c# object from xml where an element has zero or more elements of the same type? -
i'm trying parse xml file looks this:
<?xml version="1.0" encoding="utf-16" ?> <log> <request id="1" result="deny"> <user name="corp\joe"/> <session number="1"/> <file name="xyz"/> <policy type="default" name="default rules" result="deny"/> <policy type="adgroup" name="domain users" result="allow"/> </request> <request id="1" result="deny"> <user name="corp\joe"/> <session number="1"/> <file name="abc"/> <policy type="default" name="default rules" result="deny"/> <policy type="device" name="laptop12" result="deny"/> </request> </log>
note presence of multiple policy elements per request.
here's code far:
public class request { public int request_id { get; set; } public string user_name { get; set; } public string session_number { get; set; } public string file_name { get; set; } } void main() { var xml = xdocument.load(@"c:\temp\test.xml"); var query = c in xml.descendants("request") (string)c.attribute("result") == "deny" select new request() { request_id = (int) c.attribute("id"), user_name = (string) c.element("user").attribute("name"), session_number = (string) c.element("session").attribute("number"), file_name = (string) c.element("file").attribute("name"), }; foreach (request r in query.tolist()) { system.diagnostics.debug.writeline(r.user_name + "," + r.file_name); } }
i'm not sure how query , capture 0+ policy elements. should i:
- define new class policy {type, name, result}
- add list member request class
- somehow populate list when creating new request object part of linq query
it's somehow bit i'm stuck on. need add linq query within existing select, , if so, like? c.descendents("policy")...
you're on track! points correct. need policy
class , list<policy>
property in request
class. need subquery in existing query populate them:
var query = c in xml.descendants("request") (string)c.attribute("result") == "deny" select new request() { request_id = (int) c.attribute("id"), user_name = (string) c.element("user").attribute("name"), session_number = (string) c.element("session").attribute("number"), file_name = (string) c.element("file").attribute("name"), policies = (from p in c.elements("policy") select new policy() { type = (string) p.attribute("type") // (...) }).tolist() };
Comments
Post a Comment