mickthompson
mickthompson

Reputation: 5512

Java and xpath - xHtml parsing problem

I'm trying to parse a well formed xhtml document.
I'm having problems during the nodes iteration.
My xHtml has a structure like

<?xml version="1.0" encoding="UTF-8"?>
<html>
  <head>...</head>
  <body>
   ...
    <form>
    ...
      <div class="AB">    (1 or 2 times)
      ...                       
        <div class="CD">  
        ...
          <table>          
             <tbody>
                <tr>    (1 to N times)
                   <td> XXX </td>
                       <td> YYY </td> ...

The information I need is contained in the columns (td).
I want to construct N objects. So every row (tr) contains in its columns the info I need to construct an object.
I've 1 or 2 div of class="AB". So basically I'll have 1 or 2 objects AB containing a list of other objects created from every row in the table

So at first I extract a NodeList of these AB divs

NodeList ABlist= (NodeList) xpath.evaluate("//div[@class='AB']", document, XPathConstants.NODESET)

Now I'm trying to get a NodeList of all the tr elems of the first div AB.

NodeList trList = (NodeList) xpath.evaluate("/div/table//tr", ABlist.item(0), XPathConstants.NODESET);

In this case the trList is empty. Do you know what's wrong with my code?
Thank you

Upvotes: 0

Views: 1548

Answers (2)

Pavel Minaev
Pavel Minaev

Reputation: 101585

The problem in your second failing XPath is that you start it with a /:

/div/table//tr

In XPath, just as in file paths, starting a path with a / means "start from the root of the document". But you don't actually want to do that there - you want to start from your node. So:

div/table//tr

will do what you want.

Upvotes: 2

skaffman
skaffman

Reputation: 403491

Are you sure this is XHTML? There's no namespace declared in your sample document, and without that namespace, it's not XHTML. If there is a namespace, and you missed that out of your sample for brevity, then your XPath expressions need to reference the namespace also, otherwise they won't select anything.

Upvotes: 0

Related Questions