Posts Tagged ‘Java’

How to use XPath in Java

Need to use XPath in Java?
Here is a quick example, to get something from an XHTML file:

import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.w3c.tidy.Tidy;
import java.io.File;
import java.io.FileInputStream;
 
File file = new File("/abs/path/to/file");
FileInputStream xhtml = new FileInputStream(file);
 
Tidy tidy = new Tidy();
tidy.setQuiet(true);
tidy.setShowWarnings(false);
Document doc = tidy.parseDOM(xhtml, null);
 
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
 
NodeList nodes = (NodeList) xpath.evaluate("XPath Expr", doc, 
                                          XPathConstants.NODESET);
 
// NodeList nodes contains now nodes.getLength() nodes, e.g.
System.out.println(nodes.item(0).getNodeValue);
System.out.println(nodes.item(1).getTextContent();
String fst_child = nodes.item(2).getChildNodes().item(0).getNodeValue();

For more, take a look at the javax.xml.xpath package javadoc and at the NodeList interface.


Regular Expressions in Java

Need to use regular expressions (regex) for common tasks in Java?
Here is a quick example:

import java.util.regex.Pattern
import java.util.regex.Matcher
 
// ...
 
Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher("subject");
 
// find (sub)matches
while(matcher.find()) {
    String nth_match = matcher.group();
}
 
// veryfy that the whole subject matches the pattern
Boolean does_it_matches = matcher.matches()
 
// replace all the occurrence of a regex in a String (no import needed)
"string instance".replaceAll("regex","replacement");

For other tasks take a look at the Matcher class javadoc.


Return top

About me