Skip to content

Instantly share code, notes, and snippets.

@robsonfaxas
Last active June 10, 2021 23:06
Show Gist options
  • Save robsonfaxas/3498eaa6cdf7a5a794a5029419324796 to your computer and use it in GitHub Desktop.
Save robsonfaxas/3498eaa6cdf7a5a794a5029419324796 to your computer and use it in GitHub Desktop.
[LinqToXml - Consulta xml] Consultas em XML com Linq #linq #linktoxml
XDocument doc = XDocument.Load(@"C:\Curso\C#\Linq\Contatos2.xml");
IEnumerable<XElement> contatos = from c in doc.Descendants("Contato")
where c.Element("Endereco").Element("Bairro").Value == "Bairro XXX"
select c;
//Em sintaxe de método ficaria da seguinte forma:
//IEnumerable<XElement> contatos = doc.Descendants("Contato").Where(c => c.Element("Endereco").Element("Bairro").Value == "Bairro XXX");
foreach (XElement contato in contatos)
{
Console.WriteLine("{0}", contato.Element("Nome").Value);
Console.WriteLine("\nTelefones:");
XElement telefones = contato.Element("Telefones");
foreach (XElement telefone in telefones.Elements("Telefone"))
{
string tipo = telefone.Attribute("Tipo").Value;
string numero = telefone.Value;
Console.WriteLine("{0}: {1}", tipo, numero);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment