• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 476
  • Last Modified:

XML & Java / org.w3c.dom; How to get only direct child nodes. (no grandchildern)

Given the attached XML.

Suppose I'm at the outer most node. I want to get a NodeList of the childern of my current node named `A` but only direct children.

This should behave similar to the getElementsByTagName("A") method.


<A>
  <A>
  </A>
  <A>
  <A>
  </B>
  </B>
  <A>
    <A> <!-- I Don't want this one. -->
    </A>
  </A>
</A>

Open in new window

0
modsiw
Asked:
modsiw
  • 3
  • 2
1 Solution
 
CEHJCommented:
Probably easiest to use XPath. That would be pattern

./A
0
 
modsiwAuthor Commented:
Looks good. =)

Below seems to be the common usage of XPath. Please confirm?

It looks like it always uses the Document itself as the starting point of the query. Is there anyway to get it to use another node as the start point for the query?


String strQuery = "something";
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(strQuery);
NodeList nList = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);

Open in new window

0
 
modsiwAuthor Commented:
Never mind my last. Stupid question. I read examples / tutorials and not docs.

Thanks much CEHJ. I believe this will work nicely.

0
 
CEHJCommented:
:-)
0
 
modsiwAuthor Commented:
Can I use multiple XPath`s to make multiple XPathExpression`s?

If so, (And I presume I can), what would be the reason for making multiple XPath`s from a single factory?
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now