0

When i tried using the below code...the td tag is returned and not the value of the td tag.

List<?> byXPath = page2.getByXPath("//tr[@class='metadata odd']/td");
System.out.println(byXPath.get(0).toString());

For ex:If the tag is

<td class='metadata odd'>Arun</td>

The result was

<td class='metadata odd'>

.... I need the result to be Arun. Kindly help

Pascal
  • 1,288
  • 8
  • 13
Arun Kumar
  • 33
  • 2
  • 11

2 Answers2

1

Try this:

DomText domText = (DomText) form.getFirstByXPath("//tr[@class='metadata odd']/td/text()");
System.out.println(domText.getTextContent());

Edit:

If you want to get all the elements then just get them using getByXPath instead of getFirstByXPath. Then iterate over the returned List (it wasn't necessary in your question, so I didn't add that).

Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123
  • Wow...Got it... But how can i loop to the next td element? – Arun Kumar Jun 14 '12 at 14:08
  • If i give getByXPath instead of getFirstByXPath it throws an error. the above comment by nyarlathotep worked. Thanks all :) – Arun Kumar Jun 14 '12 at 14:28
  • Yeap, but that answer is just giving you the first element. My answer is the same but less wordy :P As I told you in the answer, you have to iterate over the `LIST` that returns getByXPath. – Mosty Mostacho Jun 14 '12 at 17:28
0

What you're looking for is actually the string representation of the text child node of the td tag, not the string representation of the td element itself, which you are requesting at the moment. Use a slightly different XPath expression to reference the text child node directly, like this:

List<?> byXPath = page2.getByXPath("//tr[@class='metadata odd']/td/text()");
DomText textNode = (DomText)(byXPath.get(0));
System.out.println(textNode.toString());

See also this question.

Community
  • 1
  • 1
codeling
  • 11,056
  • 4
  • 42
  • 71
  • There is no method like getFirstChild in get(0) – Arun Kumar Jun 14 '12 at 13:06
  • Value is there. When i debug the code and look for the values, the original value is present in inherited->data_, but not sure how to get that value from the data_ parameter – Arun Kumar Jun 14 '12 at 13:29
  • class com.gargoylesoftware.htmlunit.html.DomText This is the class returned. But unable to convert this to DOMMode...Sorry for making this a lengthy chat. But i am struggling past 2 hrs... – Arun Kumar Jun 14 '12 at 13:55