Java HTML / XML How to - Retrieve named parameter in XML








Question

We would like to know how to retrieve named parameter in XML.

Answer

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;
//from w  ww.  ja  v a  2s  .c o  m
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

  public static void main(String[] args) throws Exception {
    String xmlfile = "data.xml";
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(xmlfile);

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    Element element = (Element) xpath.evaluate("/root/param[@name='name2']",
        doc, XPathConstants.NODE);
    System.out.println(element.getTextContent());
  }

}