import java.io.File; import java.io.IOException; 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; import org.xml.sax.SAXException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; public class ExpressionXPath { public static void main(String[] args) { if(args.length==0){ System.out.println("usage: java ExpressionXPath xPathExp"); System.exit(1); } try { DocumentBuilderFactory fabriqueDOM = DocumentBuilderFactory.newInstance(); DocumentBuilder analyseur = fabriqueDOM.newDocumentBuilder(); Document document = analyseur.parse(System.in); XPathFactory fabriqueXPath = XPathFactory.newInstance(); XPath xpath = fabriqueXPath.newXPath(); // output with an "identity" Transformer TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); StreamResult result = new StreamResult(System.out); NodeList nodes = (NodeList)xpath.evaluate(args[0],document,XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { DOMSource source = new DOMSource(nodes.item(i)); transformer.transform(source,result); } } catch(Exception e) { e.printStackTrace(); } } }