I have a simple class (for testing purposes) that I am trying to Query against using JXPath.
I create a list of various animal objects, and I want to get an Iterator for:
All Animals where type='CAT'
All Animals where numLegs = 4
Here is the simple class:
public class Animal {
private UUID uuid;
private int numLegs;
private AnimalType type;
public enum AnimalType {
CHICKEN, FROG, DOG, CAT
}
public Animal(AnimalType type) {
this.type = type;
uuid = UUID.randomUUID();
switch (type) {
case CHICKEN:
numLegs = 2;
break;
case FROG:
numLegs = 2;
break;
case DOG:
numLegs = 4;
break;
case CAT:
numLegs = 4;
break;
}
}
public UUID getUuid() {
return uuid;
}
public int getNumLegs() {
return numLegs;
}
public AnimalType getType() {
return type;
}
public String toString(){
return "UUID: "+uuid+", Animal: "+type+ ", Legs: "+numLegs;
}
}
Here is the method I am using to build a list of Animals for me to Query against:
private static List<Animal> getAnimals(int numAnimals) {
ArrayList<Animal> animals = new ArrayList<Animal>();
for(int i = 0; i<numAnimals; i++){
if(i%4==0){
animals.add(new Animal(AnimalType.CAT));
}
else if(i%3==0){
animals.add(new Animal(AnimalType.DOG));
}
else if(i%2==0){
animals.add(new Animal(AnimalType.FROG));
}
else{
animals.add(new Animal(AnimalType.CHICKEN));
}
}
return animals;
}
Here is how I am trying to perform the query:
public static void main(String[] args){
List<Animal> animals = getAnimals(10000);
JXPathContext animsContext = JXPathContext.newContext(animals);
Iterator<BeanPointer> iter =
animsContext.iteratePointers("/*[type='CAT']");
List<Animal> cats = new ArrayList<Animal>();
while(iter.hasNext()){
cats.add((Animal) iter.next().getParent().getValue());
}
System.out.println("Number of Cats is: "+cats.size());
}
This part:
Iterator<BeanPointer> iter =
animsContext.iteratePointers("/*[type='CAT']");
is not working. What am I doing wrong? I cannot get it to work for /*[numLegs=4] either.