Java XML Element Root getRootElement(String elementName, String namespace, String prefix)

Here you can find the source of getRootElement(String elementName, String namespace, String prefix)

Description

Returns a namespaced root element of a document Useful to create a namespace holder element

License

Open Source License

Return

the root Element

Declaration

public static Element getRootElement(String elementName, String namespace, String prefix) throws Exception 

Method Source Code

//package com.java2s;
/*//from  w  w w . ja v  a 2 s.  c o m
 * Copyright (C) 2006-2016 Talend Inc. - www.talend.com
 * 
 * This source code is available under agreement available at
 * %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
 * 
 * You should have received a copy of the agreement along with this program; if not, write to Talend SA 9 rue Pages
 * 92150 Suresnes, France
 */

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

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

public class Main {
    /**
     * Returns a namespaced root element of a document Useful to create a namespace holder element
     * 
     * @return the root Element
     */
    public static Element getRootElement(String elementName, String namespace, String prefix) throws Exception {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            DOMImplementation impl = builder.getDOMImplementation();
            Document namespaceHolder = impl.createDocument(namespace,
                    (prefix == null ? "" : prefix + ":") + elementName, null); //$NON-NLS-1$ //$NON-NLS-2$
            Element rootNS = namespaceHolder.getDocumentElement();
            rootNS.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace); //$NON-NLS-1$ //$NON-NLS-2$
            return rootNS;
        } catch (Exception e) {
            String err = "Error creating a namespace holder document: " + e.getLocalizedMessage(); //$NON-NLS-1$
            throw new Exception(err);
        }
    }
}

Related

  1. getRootElement(Document parent)
  2. getRootElement(final Element descendant)
  3. getRootElement(final File definition)
  4. getRootElement(final String respuestaPost)
  5. getRootElement(final XMLEventReader bufferedXmlEventReader)
  6. getRootElement(String location)
  7. getRootElementFromString(String payload)
  8. getRootElementName(Class clazz)
  9. getRootElementPosition(String buf, Element root)