tags:

views:

820

answers:

3

Hi , I am uisng java api and using xpath to parse my xml.

I have a xml likethis -

<animals>
  <dog>
    <looks>dangerous </looks> 
     <bites> hard </bites>
     <growls> yes </growls>
  </dog>
  <cat>nothing special</cat>
</animals>

I would like a xpath condition to print

<dog>
  <looks>dangerous </looks> 
  <bites> hard </bites>
  <growls> yes </growls>
</dog>

But I am not able to now.If i use /animal/dog/text() it gives dangerous.But I guess it is used print text alone.Is there a way using xpath condition to fetch a block of xml?

EDIT :

Thanks a lot for your responses.Appreciate your time spent on this.Is there way to do it in java without printing the inner text ?

Here is where my XPATH condition goes -

public static final String XPATH_INPUT_DATA="//text()";

Thanks, Vivek

+2  A: 

If you use /animals/dog you will get back the 'dog' node with all the child nodes. Printing the inner xml of that node should give you what you need.

rslite
/animals/dog (with a s)
bortzmeyer
A: 

Demonstration of rslite's method, with the command-line tool xpath (written in Perl but it is standard Xpath, it should work everywhere):

% xpath -e /animals/dog animals.xml 
Found 1 nodes in animals.xml:
-- NODE --
<dog>
   <looks>dangerous </looks> 
   <bites> hard </bites>
   <growls> yes </growls>
</dog>
bortzmeyer
Is there way to do it in java without printing the inner text ?
A: 

All XPath does is selects a node. The //text() test just selects all text nodes from within the document. The elements exist in the document only as element nodes, and not as blocks of text as you seem to be implying. If you want to convert these elements to text then you need to make this conversion at the Java level (by printing the inner text).

Oliver Hallam