Example usage for org.w3c.dom Document getDocumentElement

List of usage examples for org.w3c.dom Document getDocumentElement

Introduction

In this page you can find the example usage for org.w3c.dom Document getDocumentElement.

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:Main.java

public static String documentToString(Document document, boolean standalone) throws Exception {
    String prol = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"" + (standalone ? "yes" : "no")
            + "\"?>";
    return prol + nodeToString(document.getDocumentElement(), new HashSet(),
            document.getDocumentElement().getNamespaceURI());
}

From source file:com.photon.phresco.impl.WindowsApplicationProcessor.java

private static void createNewItemGroup(Document doc, List<ArtifactGroup> artifactGroups) {
    Element project = doc.getDocumentElement();
    Element itemGroup = doc.createElement(ITEMGROUP);
    for (ArtifactGroup artifactGroup : artifactGroups) {
        if (artifactGroup.getType().name().equals(Type.FEATURE.name())) {
            Element reference = doc.createElement(REFERENCE);
            reference.setAttribute(INCLUDE, artifactGroup.getName());
            Element hintPath = doc.createElement(HINTPATH);
            hintPath.setTextContent(DOUBLE_DOT + COMMON + File.separator + artifactGroup.getName() + DLL);
            reference.appendChild(hintPath);
            itemGroup.appendChild(reference);
        }/*from  ww w . j  a  v a2  s  . co  m*/
    }
    project.appendChild(itemGroup);
}

From source file:com.hueemulator.lighting.utils.TestUtils.java

/**
 * Tests the DOMs represented by two XML strings for equality by performing
 * a deep comparison.//from   w ww . j ava 2s.c om
 *
 * @param xml1 represents the XML DOM to compare with xml2
 * @param xml2 represents the XML DOM to compare with xml1
 *
 * return true if the represented DOMs are equal, false otherwise
 */
public static boolean xmlsEqual(String xml1, String xml2) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc1 = db.parse(new InputSource(new StringReader(xml1)));
    Document doc2 = db.parse(new InputSource(new StringReader(xml2)));

    Set<Object> childSet1 = getChildSet(doc1.getDocumentElement(), "");
    Set<Object> childSet2 = getChildSet(doc2.getDocumentElement(), "");

    return childSet1.equals(childSet2); // comparing sets does all the hard work :)
}

From source file:net.roboconf.agent.internal.misc.UserDataUtils.java

private static String getSpecificAttributeOfTagInXMLFile(String filePath, String tagName, String attrName)
        throws ParserConfigurationException, SAXException, IOException {

    File fXmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName(tagName);
    Node aNode = nList.item(2);//  ww w.  j  av a 2  s . c o m
    NamedNodeMap attributes = aNode.getAttributes();
    String attrValue = "";
    for (int a = 0; a < attributes.getLength(); a++) {
        Node theAttribute = attributes.item(a);
        if (attrName.equals(theAttribute.getNodeName()))
            attrValue = theAttribute.getTextContent().split(":")[0];
    }

    return attrValue;
}

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Perform the migration work.//from w  w  w.  j a v a2s.co  m
 * 
 * @param document
 * @throws SiteWhereException
 */
protected static void migrateTenantConfiguration(Document document) throws SiteWhereException {
    Element beans = document.getDocumentElement();
    Element config = DomUtils.getChildElementByTagName(beans, "tenant-configuration");
    if (config == null) {
        throw new SiteWhereException("Tenant configuration element not found.");
    }
    Element dcomm = DomUtils.getChildElementByTagName(config, "device-communication");
    if (dcomm == null) {
        throw new SiteWhereException("Device communication element missing.");
    }
    Element asset = DomUtils.getChildElementByTagName(config, "asset-management");
    if (asset == null) {
        throw new SiteWhereException("Asset management element missing.");
    }
    Element eproc = DomUtils.getChildElementByTagName(config, "event-processing");
    if (eproc == null) {
        LOGGER.info("Event processing element missing. Migrating to new configuration format.");
        eproc = document.createElementNS(config.getNamespaceURI(), "event-processing");
        eproc.setPrefix(config.getPrefix());
        config.insertBefore(eproc, asset);

        moveEventProcessingElements(config, dcomm, eproc, document);
    }
    document.normalizeDocument();
}

From source file:Main.java

public static Element loadXml(final InputStream inStream) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);/*w  w w.j a  v  a 2 s .  co m*/

    Document doc;
    try {
        doc = factory.newDocumentBuilder().parse(inStream);
    } catch (SAXException e) {
        throw new IOException(e.getLocalizedMessage(), e);
    } catch (ParserConfigurationException e) {
        throw new IOException(e.getLocalizedMessage(), e);
    }

    return doc.getDocumentElement();
}

From source file:de.tub.av.pe.xcapsrv.XMLValidator.java

public static String getWellFormedElement(InputStream input)
        throws NotValidXMLFragmentConflictException, InternalServerErrorException, TransformerException,
        ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);// w  w w.  j  a v  a2s  .  co  m
    String result = null;

    DocumentBuilder parser = factory.newDocumentBuilder();
    Document dummyDocument = parser.parse(input);
    result = TextWriter.toString(dummyDocument.getDocumentElement());

    return result;
}

From source file:it.greenvulcano.gvesb.utils.ResultSetUtils.java

/**
 * Returns all values from the ResultSet as an XML.
 * For instance, if the ResultSet has 3 values, the returned XML will have following fields:
 *                                <RowSet>
 *                                  <data>
 *                                    <row>
 *                                      <col>value1</col>
 *                                      <col>value2</col>
 *                                      <col>value3</col>
 *                                    </row>
 *                                    <row>
 *                                      <col>value4</col>
 *                                      <col>value5</col>
 *                                      <col>value6</col>
 *                                    </row>
 *                                  ..//www  .  j av  a2 s  . co m
 *                                    <row>
 *                                      <col>valuex</col>
 *                                      <col>valuey</col>
 *                                      <col>valuez</col>
 *                                    </row>
 *                                  </data>
 *                                </RowSet>
 * @param rs
 * @return
 * @throws Exception
 */
public static Document getResultSetAsDOM(ResultSet rs) throws Exception {
    XMLUtils xml = XMLUtils.getParserInstance();
    try {
        Document doc = xml.newDocument("RowSet");
        Element docRoot = doc.getDocumentElement();

        if (rs != null) {
            try {
                ResultSetMetaData metadata = rs.getMetaData();
                Element data = null;
                Element row = null;
                Element col = null;
                Text text = null;
                String textVal = null;
                while (rs.next()) {
                    boolean restartResultset = false;
                    for (int j = 1; j <= metadata.getColumnCount() && !restartResultset; j++) {
                        col = xml.createElement(doc, "col");
                        restartResultset = false;
                        switch (metadata.getColumnType(j)) {
                        case Types.CLOB: {
                            Clob clob = rs.getClob(j);
                            if (clob != null) {
                                Reader is = clob.getCharacterStream();
                                StringWriter strW = new StringWriter();

                                IOUtils.copy(is, strW);
                                is.close();
                                textVal = strW.toString();
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case Types.BLOB: {
                            Blob blob = rs.getBlob(j);
                            if (blob != null) {
                                InputStream is = blob.getBinaryStream();
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                IOUtils.copy(is, baos);
                                is.close();
                                try {
                                    byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                                    textVal = new String(Base64.getEncoder().encode(buffer));
                                } catch (SQLFeatureNotSupportedException exc) {
                                    textVal = new String(Base64.getEncoder().encode(baos.toByteArray()));
                                }
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case -10: { // OracleTypes.CURSOR
                            Object obj = rs.getObject(j);
                            if (obj instanceof ResultSet) {
                                rs = (ResultSet) obj;
                                metadata = rs.getMetaData();
                            }
                            restartResultset = true;
                        }
                            break;
                        default: {
                            textVal = rs.getString(j);
                            if (textVal == null) {
                                textVal = "";
                            }
                        }
                        }
                        if (restartResultset) {
                            continue;
                        }
                        if (row == null || j == 1) {
                            row = xml.createElement(doc, "row");
                        }
                        if (textVal != null) {
                            text = doc.createTextNode(textVal);
                            col.appendChild(text);
                        }
                        row.appendChild(col);
                    }
                    if (row != null) {
                        if (data == null) {
                            data = xml.createElement(doc, "data");
                        }
                        data.appendChild(row);
                    }
                }
                if (data != null) {
                    docRoot.appendChild(data);
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (Exception exc) {
                        // do nothing
                    }
                    rs = null;
                }
            }
        }

        return doc;
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
}

From source file:de.tub.av.pe.xcapsrv.XMLValidator.java

public static Element getWellFormedDocumentFragment(Reader reader)
        throws NotValidXMLFragmentConflictException, InternalServerErrorException {
    try {//from w  w w  .j a v  a 2 s. c  o m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document dummyDocument = parser.parse(new InputSource(reader));
        return dummyDocument.getDocumentElement();
    } catch (SAXException e) {

        throw new NotValidXMLFragmentConflictException();
    } catch (IOException e) {
        throw new InternalServerErrorException(e.getMessage());
    } catch (ParserConfigurationException e) {
        throw new InternalServerErrorException(e.getMessage());
    }
}

From source file:com.impetus.kundera.ejb.PersistenceXmlLoader.java

/**
* Find persistence units./*from   ww w .j av  a2s  . c o  m*/
* 
* @param url
*            the url
* @param defaultTransactionType
*            the default transaction type
* @return the list
* @throws Exception
*             the exception
*/
public static List<PersistenceMetadata> findPersistenceUnits(URL url,
        PersistenceUnitTransactionType defaultTransactionType) throws Exception {

    Document doc = getDocument(url);
    Element top = doc.getDocumentElement();
    NodeList children = top.getChildNodes();
    ArrayList<PersistenceMetadata> units = new ArrayList<PersistenceMetadata>();

    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) children.item(i);
            String tag = element.getTagName();
            // look for "persistence-unit" element
            if (tag.equals("persistence-unit")) {
                PersistenceMetadata metadata = parsePersistenceUnit(element);
                units.add(metadata);
            }
        }
    }
    return units;
}