Get data from an XML file, using XPath and C #

1

I have the following document XML , and I want to do a search / filter by name GivenName using Xpath . How to do?

XML

<bloodonors>
  <donor>
    <Number>1</Number>
    <Gender>male</Gender>
    <GivenName>Estevan</GivenName>
    <Surname>Rodrigues</Surname>
  </donor>
  <donor>
    <Number>2</Number>
    <Gender>female</Gender>
    <GivenName>Lucy</GivenName>
    <Surname>Silva</Surname>
  </donor>
  <donor>
    <Number>3</Number>
    <Gender>female</Gender>
    <GivenName>Beatriz</GivenName>
    <Surname>Santos</Surname>
  </donor>
</bloodonors>

My code

XmlDocument doc = new XmlDocument();
doc.Load(@ "Dadores.xml");
XmlNode root = doc.DocumentElement; //seleciona elemento do documento
XmlNodeList listaDador = root.SelectNodes("/bloodonors/donor[GivenName[contains(.,'" + GivenName + "'0] or Surname[contains(.,'" + Surname + "'0]");
    
asked by anonymous 07.11.2017 / 10:23

1 answer

0

XmlNode.SelectNodes Method

  

Selects a list of nodes that correspond to the XPath expression.

Your code should look like this:

 XmlDocument doc = new XmlDocument();
 doc.Load("EnderecoArquivo");
 XmlNode root = doc.DocumentElement; //seleciona elemento do documento
 XmlNodeList listaDador = root.SelectNodes("//donor[contains(GivenName,'Este')]");
 List < XmlNode > listOfNodes = new List < XmlNode > (listaDador.Cast < XmlNode > ());

 listOfNodes.ForEach(i => Console.WriteLine(i.InnerXml));

Result:

<Number>1</Number><Gender>male</Gender><GivenName>Estevan</GivenName><Surname>Rodrigues</Surname>
    
07.11.2017 / 11:56