dom4j: How to resolve this XPath Error?

5k Views Asked by At

I am reading an XML using dom4j by using XPath techniques for selecting desired nodes. Consider that my XML looks like this:

<Emp_Dir>
    <Emp_Classification type ="Permanent" >
        <Emp id= "1">
        <name>jame</name>
            <Emp_Bio>
                <age>12</age>
                <height>5.4</height>
        <weight>78</weight>
            </Emp_Bio>
            <Emp_Details>
                <salary>2000</salary>
        <designation>developer</designation>
            </Emp_Details>
        </Emp>
        <Emp id= "2">
        <name>jame</name>
            <Emp_Bio>
                <age>12</age>
                <height>5.4</height>
        <weight>78</weight>
            </Emp_Bio>
            <Emp_Details>
                <salary>2000</salary>
        <designation>developer</designation>
            </Emp_Details>
        </Emp>
    </Emp_Classification>

    <Emp_Classification type ="Contract" >
    .
    .
    .
    </Emp_Classification>

    <Emp_Classification type ="PartTime" >
    .
    .
    .
    </Emp_Classification>
</Emp_Dir>

Note: The above XML might looks ugly to you but i only create this dummy file for the sake of understanding and keeping the secracy of my project

When i specify some simple XPath expression, like:

//Emp_Classification (or)
/Emp_Dir/Emp_Classification

then its works fine but when i specify some complex expression like:

/Emp_Dir/Emp_Classification/[@type='Permanent'] (or)
//Emp_Dir/Emp_Classification/[@type='Permanent']

then it gives me the following error:

"Invalid XPath expression: /Emp_Dir/Emp_Classification/[@type='Permanent'] Expected one of '.', '..', '@', '*', <QName>"

Coulde anybody guides me what goes wrong in my XPath?

My second question is that how do i select the Emp_Bio node of Permanent Employees only, does this works?

//Emp_Dir/Emp_Classification/[@type='Permanent']/Emp/Emp_Bio
1

There are 1 best solutions below

0
On BEST ANSWER

Use : //Emp_Dir/Emp_Classification[@type='Permanent']

(note the removal of /)

And then use this : //Emp_Dir/Emp_Classification[@type='Permanent']/Emp/Emp_Bio for the latter part of the question.