Что ты уже пробовал? Вот что вы можете попробовать:
- Получите предков вашего узла с
//Node[@id='16']/ancestor::Node
- Переберите этот NodeList и создайте набор правил, когда вы читаете атрибуты узлов
- когда последний предок получает последний узел и получает из него оценку
- распечатать то, что вы нашли
Вот пример, использующий только стандартный jdk, но у вас может возникнуть желание использовать что-то вроде dom4j :
public class SO9466408 {
private static final Map<String, String> OP = new HashMap<String, String>() {{ put("lessOrEqual", "<="); }};
public static String attrValue(Node node, String attrName) {
return node.getAttributes().getNamedItem(attrName).getTextContent();
}
public static void main(String[] args) throws XPathExpressionException {
final String id = "16";
String score = null;
final StringBuilder ruleset = new StringBuilder("if (");
// XML/XPath
final InputSource xmlInput = new InputSource(new URL("your file.xml").openStream());
final XPath xpath = XPathFactory.newInstance().newXPath();
// get the ancestors node
final XPathExpression expr = xpath.compile("//Node[@id='" + id + "']/ancestor::Node");
final NodeList ancestors = (NodeList) expr.evaluate(xmlInput, XPathConstants.NODESET);
for (int i = 0; i < ancestors.getLength(); ++i) {
Node predicate = ancestors.item(i).getFirstChild();
// get a new rule
if (predicate.getNodeName().equals("SimplePredicate")) {
ruleset.append(String.format("%s(%s %s %s)", i > 1 ? " && " : "",
attrValue(predicate, "field"), OP.get(attrValue(predicate, "operator")), attrValue(predicate, "value")));
}
// retrieve the score on the last node
if (i == ancestors.getLength() - 1) {
score = attrValue((Node) xpath.compile("//Node[@id='" + id + "']").evaluate(ancestors.item(i), XPathConstants.NODE), "score");
}
}
// show what we found
ruleset.append(") {\n\tscore = " + score + ";\n}");
System.out.println(ruleset.toString());
}
}
// Outputs:
// if ((GRAVH.1 <= 2751.5996775) && (WV.unity <= 93.567676535) && (Zagreb <= 74))
// {
// score = 2.32
// }