0

I am going to check that if a dom tree java object contains another dom tree java object or not? what is the most efficient way of doing that?

If I use recursive method for that probably the whole process would be really time consuming so is there any efficient way for traversing DOM tree for check this?

For example take a look at this xml:

<a class='x'>Hello
<b>How are you?</b>
<a class='x'>I am fine!</a>
</field1>

When I use xpath ".//*[@class='x']" two node would be selected that one of them is parent of the another one. I want to select the parent one only. For this purpose somehow I have to check whether one of the selected nodes (which are both DOM tree) is a child of another DOM tree or not.

Ali
  • 1,759
  • 2
  • 32
  • 69
  • A Document is rooted at a Node, so any Element could be the root of another Document. If you have unmarshalled an XML document, there would not be any indication of some Element being another DOM tree's root. Not sure what you are asking here. – laune Dec 28 '14 at 09:53
  • Dear @laune I edited the question. Hope it is clear now. – Ali Dec 28 '14 at 11:11

1 Answers1

0

You'll have to do a breadth-first search on the document anyway to locate an element (or elements) at some minimum depth. This will give you one or more elements with @class="x". You can stop here, if that's all you want to know. If you want to continue, exclude these elements from the set of nodes to be investigated in the next iteration.

laune
  • 31,114
  • 3
  • 29
  • 42
  • This is not fast enough in worst case scenario. – Ali Dec 28 '14 at 13:21
  • Well, selecting all nodes by evaluating XPath `.//*[@class='x']` is going to take some time, and if you are investigating this result, it'll take even longer. - How big is your document? – laune Dec 28 '14 at 13:24