forked from patniemeyer/learningjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXMLGrep.java
More file actions
47 lines (39 loc) · 1.37 KB
/
Copy pathXMLGrep.java
File metadata and controls
47 lines (39 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import javax.xml.xpath.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class XMLGrep {
public static void printXML( Element element ) throws TransformerException
{
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
Source source = new DOMSource( element );
Result output = new StreamResult( System.out );
transformer.transform( source, output );
System.out.println();
}
public static void main( String [] args ) throws Exception
{
/*
if ( args.length != 2 ) {
System.out.println( "usage: PrintXPath expression file.xml" );
System.exit(1);
}
String expression = args[0], filename = args[1];
*/
String expression = "//animal[starts-with(name,'C')]";
String filename = "zooinventory.xml";
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource( filename );
NodeList elements = (NodeList)xpath.evaluate(
expression, inputSource, XPathConstants.NODESET );
for( int i=0; i<elements.getLength(); i++ )
if ( elements.item(i) instanceof Element ) {
printXML( (Element)elements.item(i) );
} else
System.out.println( elements.item(i) );
}
}