3

DOMで特定のキーワードを検索し、それが見つかったら、ツリー内のどのノードからのものかを知りたい。

static void search(String segment, String keyword) {

    if (segment == null)
        return;

    Pattern p=Pattern.compile(keyword,Pattern.CASE_INSENSITIVE);
    StringBuffer test=new StringBuffer (segment);
    matcher=p.matcher(test);

    if(!matcher.hitEnd()){        
        total++;
        if(matcher.find())
        //what to do here to get the node?
    }
}

public static void traverse(Node node) {
    if (node == null || node.getNodeName() == null)
        return;

    search(node.getNodeValue(), "java");

    check(node.getFirstChild());

    System.out.println(node.getNodeValue() != null && 
                       node.getNodeValue().trim().length() == 0 ? "" : node);
    check(node.getNextSibling());
}
4

1 に答える 1

3

XPathAPI)の使用を検討してください。

// the XML & search term
String xml = "<foo>" + "<bar>" + "xml java xpath" + "</bar>" + "</foo>";
InputSource src = new InputSource(new StringReader(xml));
final String term = "java";
// search expression and term variable resolver
String expression = "//*[contains(text(),$term)]";
final QName termVariableName = new QName("term");
class TermResolver implements XPathVariableResolver {
  @Override
  public Object resolveVariable(QName variableName) {
    return termVariableName.equals(variableName) ? term : null;
  }
}
// perform the search
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setXPathVariableResolver(new TermResolver());
Node node = (Node) xpath.evaluate(expression, src, XPathConstants.NODE);

正規表現を介してより複雑なマッチングを実行する場合は、独自の関数リゾルバーを提供できます。

XPath式の内訳//*[contains(text(),$term)]

  • //*アスタリスクは任意の要素を選択します。ダブルスラッシュは任意の親を意味します
  • [contains(text(),$term)]テキストに一致する述語です
  • text()要素のテキストを取得する関数です
  • $term変数です。これは、変数リゾルバーを介して「java」という用語を解決するために使用できます。インジェクション攻撃を防ぐために、文字列連結よりもリゾルバーが推奨されます(SQLインジェクションの問題と同様)
  • contains(arg1,arg2)arg1にarg2が含まれている場合にtrueを返す関数です

XPathConstants.NODE単一のノードを選択するようにAPIに指示します。を使用NODESETして、すべての一致をとして取得できますNodeList

于 2011-11-23T10:21:20.067 に答える