Java XML Element Root getRoot(Document document)

Here you can find the source of getRoot(Document document)

Description

get Root

License

Open Source License

Declaration

public static Element getRoot(Document document) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

import org.w3c.dom.NodeList;

public class Main {
    public static Element getRoot(String path) {
        return getRoot(new File(path));
    }// w  w w .j  a v a2 s. c o m

    public static Element getRoot(File file) {
        return getRoot(loadXMLDocument(file));
    }

    public static Element getRoot(Document document) {
        return getRoot(document, "root");
    }

    public static Element getRoot(Document document, String root) {
        if (document == null) {
            throw new IllegalArgumentException("Null document");
        }

        NodeList nodeList = document.getElementsByTagName(root);
        return nodeList.item(0) != null ? (Element) nodeList.item(0) : null;
    }

    public static Document loadXMLDocument(String path) {
        return loadXMLDocument(new File(path));
    }

    public static Document loadXMLDocument(File file) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);
            return document;
        } catch (Exception ex) {
            return null;
        }
    }
}

Related

  1. getElementText(String elemName, Element root, boolean trim)
  2. getElementValue(Element root, String name)
  3. getElementValueLong(Element root, String name)
  4. getRoot(Document doc)
  5. getRoot(Document doc)
  6. getRoot(final Document doc)
  7. getRoot(SOAPElement e)
  8. getRootElement(Document d)
  9. getRootElement(Document doc)