Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. The ASF licenses this file to You 
 * under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License.  
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    /**
     * Traverses the DOM tree to lookup the XPath.
     * 
     * A sample XPath would look like "Parent > Child > Grandchild" for a DOM
     * tree as following:
     * 
     * <pre>
     * <Parent>
     *       <Child>
     *          <Grandchild>
     *          </Grandchild>
     *       </Child>
     * </Parent>
     * </pre>
     * 
     * @param doc
     *            The DOM tree to traverse
     * @param xPath
     *            A path to lookup
     * @param separator
     *            String separator used to break up level hierarchy with in the
     *            path
     * @return Node(s) found at the given path
     */
    public static NodeList lookup(Document doc, String xPath, String separator) {
        return lookup(doc.getDocumentElement(), xPath, separator);
    }

    /**
     * Traverses the DOM tree to lookup the XPath.
     * 
     * A sample XPath would look like "Parent > Child > Grandchild" for a DOM
     * tree as following:
     * 
     * <pre>
     * <Parent>
     *       <Child>
     *          <Grandchild>
     *          </Grandchild>
     *       </Child>
     * </Parent>
     * </pre>
     * 
     * @param e
     *            The DOM element to look under
     * @param xPath
     *            A path to lookup
     * @param separator
     *            String separator used to break up level hierarchy with in the
     *            path
     * @return Node(s) found at the given path
     */
    public static NodeList lookup(Element e, String xPath, String separator) {
        String[] trail = { xPath };
        if (separator != null) {
            trail = xPath.split(separator);
        }
        Element parent = e;
        for (int i = 0; i < trail.length - 1; i++) {
            parent = (Element) parent.getElementsByTagName(trail[i].trim()).item(0);
        }
        return parent.getElementsByTagName(trail[trail.length - 1].trim());
    }
}