Retrieve data from an XML file using Xpath and C#

Asked

Viewed 68 times

1

I have the following document XML, and I intend 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]");
  • What have you tried ? What errors are appearing ?

  • I tried using Selectnodes, but I’m not getting it, I’ve searched the web, and I can’t find anything, this is my last resort

  • @Blazin put the code in C# that tried!

  • p.s - I am not very good at programming, I started a short time, hence I need project help

  • @Marconi already put in question the code I tried to use

  • @Blazin at first is just like that, I’ll try to help you around here if there’s not a likely answer that put one! Welcome to Stack overflow, recommend reading on tour to understand a little more how things work around here.

  • @Blazin added an answer!

  • @Blazin If Marconi’s answer solves your problem, mark it as accepted/correct.

Show 4 more comments

1 answer

0


Xmlnode method.Selectnodes

Selects a list of nodes that match the Xpath expression.

Your code must be 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));

Upshot:

<Number>1</Number><Gender>male</Gender><GivenName>Estevan</GivenName><Surname>Rodrigues</Surname>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.