Returns the element with the specified tag name. - Java XML

Java examples for XML:DOM Element

Description

Returns the element with the specified tag name.

Demo Code

/**//w  w w  . jav a 2  s . com
 * Copyright (c) 2009 DITA2InDesign project (dita2indesign.sourceforge.net)  Licensed 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 java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Main{
    /**
     * Returns the element with the specified tag name.
     *
     * Throws an exception if element not found or if more than one found.
     */
    public static Element getElement(Element parentElem, String tagName)
            throws DataUtilException {
        NodeList nl = parentElem.getElementsByTagName(tagName);
        if (nl.getLength() == 0) {
            throw new DataUtilException("No " + tagName + " element found");
        }
        if (nl.getLength() > 1) {
            throw new DataUtilException("Found more than one " + tagName
                    + " elements");
        }
        Element result = (Element) nl.item(0);
        return result;
    }
}

Related Tutorials