如何检查XMLTree并返回

时间:2014-10-31 02:16:15

标签: java xml recursion

我无法弄清楚为什么这会给出错误的值。

public static void main(String[] args) {
    SimpleReader in = new SimpleReader1L();
    SimpleWriter out = new SimpleWriter1L();
    boolean x = true;
    out.print("Enter a URL or file name for an XML source: ");
    String url = in.nextLine();
    XMLTree xml = new XMLTree2(url);
    out.print("Enter the name of a tag: ");
    String tag = in.nextLine();
    out.println(findTag(xml, tag));
}

/**
 * Reports whether the given tag appears in the given {@code XMLTree}.
 * 
 * @param xml
 *            the {@code XMLTree}
 * @param tag
 *            the tag name
 * @return true if the given tag appears in the given {@code XMLTree}, false
 *         otherwise
 * @ensures <pre>
 * findTag =
 *    [true if the given tag appears in the given {@code XMLTree}, false otherwise]
 * </pre>
 */
private static boolean findTag(XMLTree xml, String tag) {
    boolean result = false;
    if (xml.isTag()) {
        for (int i = 0; i < xml.numberOfChildren(); i++) {

            findTag(xml.child(i), tag);
            System.out.println("label is " + xml.label());
            if (xml.label().equals(tag)) {
                result = true;
                System.out.println(result);
            }
        }
    }

    return result;
}

}

当给定一个xml树时,代码会运行,以便找到树中存在的所有标记。它将每个标记与正在搜索的标记进行比较。如何使它在XML中找到给定标记时更新布尔变量并阻止它搜索更多。

1 个答案:

答案 0 :(得分:0)

有两种方法可以做你想做的事。

1)。将boolean变量设为方法的静态全局变量。

2)。将boolean变量作为method传递给argument。  在处理方法之前,只需检查变量的状态。

像这样的东西

private static boolean findTag(XMLTree xml, String tag,boolean result) {       
    if (xml.isTag() && !result) {
        for (int i = 0; i < xml.numberOfChildren(); i++) {

            findTag(xml.child(i), tag,result);
            System.out.println("label is " + xml.label());
            if (xml.label().equals(tag)) {
                result = true;
                System.out.println(result);
                return result;
            }
        }
    }

    return result;
}