Java HTML / XML How to - Search xml element by id








Question

We would like to know how to search xml element by id.

Answer

import java.io.File;
// w ww.  j a va2s  . c o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("filename.xml"));

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    Element element = (Element) xpath.evaluate("//*[@id='one']", document,
        XPathConstants.NODE);
  }

}