Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>[email protected]</email>
    <confirmado>SI</confirmado>
  </contact>
  <contact type="1" id="2">
    <name>Name2</name>
    <email>[email protected]</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?

like image 867
Kiquenet Avatar asked Dec 28 '22 04:12

Kiquenet


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

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.

like image 173
dtb Avatar answered Jan 11 '23 16:01

dtb


You could use LINQ:

foreach (XElement element in doc.Descendants("contact").Where(c => c.Element("confirmado").Value == "SI"))
like image 41
Paul Abbott Avatar answered Jan 11 '23 17:01

Paul Abbott