how can is get the nodelist of child node using xpath dom java?

tharani dharan picture tharani dharan · Feb 8, 2012 · Viewed 20.7k times · Source
<a>
    <b>
        <c type="lol">
            <d>1</d>
            <f>2</f>
        </c>
        <c type="lol">
            <d>2</d>
            <f>2</f>
        </c>
        <c type="h">
            <d>v</d>
            <f>d</f>
        </c>
    </b>
</a>

 

DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dB = dBFactory.newDocumentBuilder();
Document doc = dB.parse(url);     
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

how can is get the nodelist of child node i.e i need to get the child nodes of "b"(nodelist which has 3 "c" nodes )..

Answer

Lukas Eder picture Lukas Eder · Feb 8, 2012

You could use jOOX and then write

List<Element> elements = $(doc).find("b").children().get();

Or with DOM:

// Beware, this list also contains the blank text nodes around the <c/> elements,
// if your document is formatted.
NodeList list = doc.getElementsByTagName("b").item(0).getChildNodes();

UPDATE: If you want to further traverse your DOM document (i.e. get the child nodes of "c" as you mention in your comments, then I really recommend jOOX:

// This will find all "c" elements, and then return all children thereof
$(doc).find("c").children();

// This will return "d", "f", "d", "f", "d", "f":
List<String> tags = $(doc).find("c").children().tags();

// This will return "1", "2", "2, "2", "v", "d":
List<String> texts = $(doc).find("c").children().texts();

Doing the same with DOM will become quite verbose:

List<Element> elements = new ArrayList<Element>();
List<String> tags = new ArrayList<String>();
List<String> texts = new ArrayList<String>();

NodeList c = doc.getElementsByTagName("c");
for (int i = 0; i < c.getLength(); i++) {
  if (c.item(i) instanceof Element) {
    NodeList children = c.item(i).getChildNodes();

    for (int j = 0; j < children.getLength(); j++) {
      if (children.item(j) instanceof Element) {
        elements.add((Element) children.item(j));
        tags.add(((Element) children.item(j)).getTagName());
        texts.add(children.item(j).getTextContent());
      }
    }
  }
}

UPDATE 2 (please be more specific with your future questions...!): With XPath, do this:

XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile("//c/*");
NodeList nodes = (NodeList) expression.evaluate(
  document.getDocumentElement(), XPathConstants.NODESET);