Home > Software design >  Return the value of XML with for loop not the number, using Xquery
Return the value of XML with for loop not the number, using Xquery

Time:02-21

Im using http://xpatheval.apphb.com/ this site, which works perfectly, I just have a problem with code and getting the value that I need. I have an XML code here:

<?xml version="1.0"?>
<RIGA>
   <STREET Name="Brivibas">
      <HOUSE No="1">
         <FLAT No="1">
            <INHABITANT Year="1970" Gender="M">Ivanovs Sergejs</INHABITANT>
            <INHABITANT Year="1970" Gender="F">Ivanova Anna</INHABITANT>
         </FLAT>
         <FLAT No="2">
            <INHABITANT Year="1972" Gender="M">Strods Janis</INHABITANT>
            <INHABITANT Year="1972" Gender="F">Strode Inna</INHABITANT>
            <INHABITANT Year="1974" Gender="F">Strode Julija</INHABITANT>
         </FLAT>
      </HOUSE> 
      <HOUSE No="2">
         <FLAT No="1">
            <INHABITANT Year="1974" Gender="M">Zemzars Uldis</INHABITANT>
         </FLAT>
      </HOUSE> 
   </STREET>
   <STREET Name="Elizabetes">
      <HOUSE No="1">
         <FLAT No="1">
            <INHABITANT Year="1985" Gender="M">Celms Juris</INHABITANT>
         </FLAT>
         <FLAT No="2">
            <INHABITANT Year="1988" Gender="M">Dmitrijevs Igors</INHABITANT>
            <INHABITANT Year="1988" Gender="F">Dmitrijeva Svetlana</INHABITANT>
            <INHABITANT Year="1989" Gender="F">Dmitrijeva Olga</INHABITANT>
            <INHABITANT Year="1989" Gender="M">Dmitrijevs Pjotrs</INHABITANT>
         </FLAT>
      </HOUSE> 
   </STREET>
</RIGA>

And the Xquery code I wrote is this:

<MALES>
{let $male:=//INHABITANT[@Gender="M"]
for $male in (1 to 6)
return <MALE>{$male}</MALE>}
</MALES>

Im getting:

<MALES>
   <MALE>1</MALE>
   <MALE>2</MALE>
   <MALE>3</MALE>
   <MALE>4</MALE>
   <MALE>5</MALE>
   <MALE>6</MALE>
</MALES>

But what I need is:

<MALES>
   <MALE>First Name Last Name</MALE>
   <MALE>First Name Last Name</MALE>
   <MALE>First Name Last Name</MALE>
   <MALE>First Name Last Name</MALE>
   <MALE>First Name Last Name</MALE>
   <MALE>First Name Last Name</MALE>
</MALES>

Where have I made a mistake in my code?

I have 0 experience using XML and Xquery

CodePudding user response:

Instead of the numbers 1 to 6, you’ll need to bind the text node of the XPath expression to the variable:

<MALES>{
  for $male in //INHABITANT[@Gender = "M"]/text()
  return <MALE>{ $male }</MALE>
}</MALES>
  • Related