santhosh-tekuri/jlibs

Sax2Binding can't parse attributes in elements without child

LiashenkoVitalii opened this issue · 2 comments

I tried to use the lib and found out that it can't parse something like this:

<employee>                     
    <name>scott</name>         
    <age>20</age>              
    <experience measure="years">5</experience> 
</employee>

So, when I need a value for an attribute "measure" I can create a binding for "experience" or I just can get value for "experience" but not both values at the same time. I think this case should be very commonly used and maybe I just couldn't find some workaround for it?

below is sample binding code to read the xml you mentioned.
see ExperienceBinding: you can get both values at same time.

the documentation page may not cover all cases.
you can see documentation of annotations to see the supported method signature.

public class Employee {
    public String name;
    public int age;
    public Experience experience;
}

public class Experience {
    public int value;
    public String unit;
}

@Binding("employee")
public class EmployeeBinding {
    @Binding.Start
    public static Employee onStart() {
        return new Employee();
    }

    @Binding.Text({"name", "age", "experience"})
    public static String onText(String text){
        return text;
    }

    @Relation.Finish("name")
    public static void relateName(Employee employee, String name){
        employee.name = name;
    }

    @Relation.Finish("age")
    public static void relateAge(Employee employee, String age){
        employee.age = Integer.parseInt(age);
    }

    @Binding.Element(element = "experience", clazz = ExperienceBinding.class)
    public static void onExperience(){}

    @Relation.Finish("experience")
    public static void relateExperience(Employee employee, Experience experience){
        employee.experience = experience;
    }
}

@Binding("experience")
public class ExperienceBinding {
    @Binding.Start
    public static Experience onStart(@Attr String measure){
        Experience experience = new Experience();
        experience.unit = measure;
        return experience;
    }

    @Binding.Text
    public static void onText(Experience experience, String text){
        experience.value = Integer.parseInt(text);
    }
}

Thank you very much! It works for me, but I couldn't guess how to do it on my own