public XPathExpression(String s) { Matcher m = pattern.matcher(s); while (m.find()) { String[] arr = m.group(1).split("=", 2); String command = arr[0].trim(); String result = arr[1].trim(); if ((result.startsWith("\"") && result.endsWith("\"")) || (result.startsWith("'") && result.endsWith("'"))) { result = result.substring(1, result.length() - 1); } if (this.command == null) { this.command = command; this.result = result; } if (next == null) { next = new XPathExpression(command, result); } else { XPathExpression next = this.next; while (next.next != null) { next = next.next; } next.next = new XPathExpression(command, result); } } }
public boolean check(Node n) { boolean b = false; if (command.equals("text()")) { b = result.equals(n.text()); } else if (command.startsWith("@")) { b = result.equals(n.attr(command.substring(1))); } return b && (next == null || next.check(n)); } }
public List<Node> getAll(String path) { List<Node> list = new ArrayList<Node>(); if (children == null || path == null) return list; int l = path.indexOf('/'); if (l == -1) { l = path.indexOf("["); XPathExpression exp = null; if (l != -1) { exp = new XPathExpression(path.substring(l, path.length())); path = path.substring(0, l); } for (Node node : children) { if (node.name != null && node.name.equals(path) && (exp == null || exp.check(node))) list.add(node); } } else { String tag = path.substring(0, l); path = path.substring(l + 1); for (Node node : children) { if (node.name != null && node.name.equals(tag)) { List<Node> r = node.getAll(path); if (r != null) list.addAll(r); } } } return list; }
public Node get(String path) { if (children == null || path == null) return null; int l = path.indexOf('/'); if (l == -1) { l = path.indexOf("["); XPathExpression exp = null; if (l != -1) { exp = new XPathExpression(path.substring(l, path.length())); path = path.substring(0, l); } for (Node node : children) { if (node.name != null && node.name.equals(path) && (exp == null || exp.check(node))) return node; } } else { String tag = path.substring(0, l); path = path.substring(l + 1); for (Node node : children) { if (node.name != null && node.name.equals(tag)) { Node r = node.get(path); if (r != null) return r; } } } return null; }