c# - Filter XDocument more efficiently -
i filter high performance xml elements xml document.
take instance xml file contacts:
<?xml version="1.0" encoding="iso-8859-1"?> <?xml-stylesheet type="text/xsl" href="asistentes.xslt"?> <contactlist evento="cena navidad 2010" empresa="company"> <contact type="1" id="1"> <name>name1</name> <email>xxxx@zzzz.es</email> <confirmado>si</confirmado> </contact> <contact type="1" id="2"> <name>name2</name> <email>xxxxxxxxx@zzzze.es</email> <confirmado>sin confirmar</confirmado> </contact> </contaclist>
my current code filter xml document:
using system; using system.xml.linq; class test { static void main() { string xml = @" xml above"; xdocument doc = xdocument.parse(xml); foreach (xelement element in doc.descendants("contact")) { console.writeline(element); var id = element.attribute("id").value; var valor = element.descendants("confirmado").tolist()[0].value; var email = element.descendants("email").tolist()[0].value; var name = element.descendants("name").tolist()[0].value; if (valor.tostring() == "si") { } } } }
what best way optimize code filter on <confirmado>
element content?
var doc = xdocument.parse(xml); var query = contact in doc.root.elements("contact") let confirmado = (string)contact.element("confirmado") confirmado == "si" select new { id = (int)contact.attribute("id"), name = (string)contact.element("name"), email = (string)contact.element("email"), valor = confirmado }; foreach (var contact in query) { ... }
points of interest:
doc.root.elements("contact")
selects<contact>
elements in document root, instead of searching whole document<contact>
elements.the xelement.element method returns first child element given name. no need convert child elements list , take first element.
the xelement , xattribute classes provide wide selection of convenient conversion operators.
Comments
Post a Comment