Filter XDocument more efficiently

I would like to filter using high-performance XML elements from an XML document.

Take, for example, this XML file with 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 to filter from this XML document is:

 using System; using System.Xml.Linq; class Test { static void Main() { string xml = @" the 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 would be the best way to optimize this code to filter the contents of <confirmado> elements?

+4
source share
2 answers
 var doc = XDocument.Parse(xml); var query = from contact in doc.Root.Elements("contact") let confirmado = (string)contact.Element("confirmado") where 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) { ... } 

Sights:

  • doc.Root.Elements("contact") selects only the <contact> elements in the document root, instead of finding the entire document for the <contact> elements.

  • The XElement.Element method returns the first child with the given name. There is no need to convert child elements to a list and accept the first element.

  • The XElement and XAttribute classes provide a wide selection of convenient conversion operators .

+9
source

You can use LINQ:

 foreach (XElement element in doc.Descendants("contact").Where(c => c.Element("confirmado").Value == "SI")) 
0
source

All Articles