Java by API/javax.xml.xpath/XPathFactory

Материал из Java эксперт
Версия от 14:15, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

XPathFactory: newInstance()

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MainClass {
  public static void main(String[] args) throws ParserConfigurationException,
      XPathExpressionException, org.xml.sax.SAXException, java.io.IOException {
    String documentName = args[0];
    String expression = args[1];
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = parser.parse(new java.io.File(documentName));
    XPath xpath = XPathFactory.newInstance().newXPath();
    System.out.println(xpath.evaluate(expression, doc));
    NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
    for (int i = 0, n = nodes.getLength(); i < n; i++) {
      Node node = nodes.item(i);
      System.out.println(node);
    }
  }
}





XPathFactory: newXPath()

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MainClass {
  public static void main(String[] args) throws ParserConfigurationException,
      XPathExpressionException, org.xml.sax.SAXException, java.io.IOException {
    String documentName = args[0];
    String expression = args[1];
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = parser.parse(new java.io.File(documentName));
    XPath xpath = XPathFactory.newInstance().newXPath();
    System.out.println(xpath.evaluate(expression, doc));
    NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
    for (int i = 0, n = nodes.getLength(); i < n; i++) {
      Node node = nodes.item(i);
      System.out.println(node);
    }
  }
}