Filter XDocument more efficiently

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

Take for instance 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:

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 on <confirmado> element content?

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)
{
    ...
}

Points of interest:

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

  • The XElement.Element method returns the first child element with the given name. No need to convert the child elements to a list and take the first element.

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


Need Your Help

android memory leak detection

android eclipse memory-leaks

The ADT eclipse plugin will report memory leaks when I run the android application (when it has leaks in it). How does the VM (or the plugin) detect memory leaks at run-time? What is the detection

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.