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开发者_如何学Python="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?
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. 
You could use LINQ:
foreach (XElement element in doc.Descendants("contact").Where(c => c.Element("confirmado").Value == "SI"))
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论