51 lines
1.4 KiB
Java
51 lines
1.4 KiB
Java
package eu.dnetlib.miscutils.dom4j; // NOPMD
|
|
|
|
import java.io.StringReader;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
import org.dom4j.Document;
|
|
import org.dom4j.DocumentException;
|
|
import org.dom4j.Element;
|
|
import org.dom4j.Node;
|
|
import org.dom4j.io.SAXReader;
|
|
|
|
import eu.dnetlib.miscutils.collections.TypeFilteredCollection;
|
|
|
|
/**
|
|
* This class allows to avoid casts and unnecessary suppress warnings statements which would be necessary when using the dom4j API.
|
|
*
|
|
* @author marko
|
|
*
|
|
*/
|
|
public class XPathHelper {
|
|
public static Iterable<Element> selectElements(final Node base, final String xpath) {
|
|
@SuppressWarnings("unchecked")
|
|
final List<Node> children = base.selectNodes(xpath);
|
|
return new TypeFilteredCollection<Node, Element>(children, Element.class);
|
|
}
|
|
|
|
public static Iterable<Element> selectElements(final String base, final String xpath) {
|
|
Document document;
|
|
try {
|
|
document = new SAXReader().read(new StringReader(base));
|
|
return selectElements(document, xpath);
|
|
} catch (DocumentException e) {
|
|
return new ArrayList<Element>();
|
|
}
|
|
}
|
|
|
|
public static Element selectElement(final Node base, final String xpath) {
|
|
for (Element el : selectElements(base, xpath))
|
|
return el;
|
|
return null;
|
|
}
|
|
|
|
public static Element selectElement(final String base, final String xpath) {
|
|
for (Element el : selectElements(base, xpath))
|
|
return el;
|
|
return null;
|
|
}
|
|
|
|
}
|