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 Document getDocument(String xmlStr) {
    docFactory = getInstance();/*w w  w.j  a v a  2s  . c om*/
    Document document = null;
    try {
        DocumentBuilder builder = docFactory.newDocumentBuilder();
        document = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        document.getDocumentElement().normalize();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return document;
}

From source file:Main.java

/**
 * Parses a string into an XMLDocument//from  www .  j ava2  s  .c  o m
 * 
 * @param xmlString
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public static Document loadXML(String xmlString)
        throws IOException, ParserConfigurationException, SAXException {
    InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputStream);

    // optional, but recommended
    // read this -
    // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    return doc;
}

From source file:edu.gslis.ts.ChunkToFile.java

public static Map<Integer, FeatureVector> readEvents(String path, Stopper stopper) {
    Map<Integer, FeatureVector> queries = new TreeMap<Integer, FeatureVector>();

    try {/*  w w w  .  j  ava  2s  . c  o  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(new File(path));

        NodeList events = doc.getDocumentElement().getElementsByTagName("event");
        for (int i = 0; i < events.getLength(); i++) {
            Node event = events.item(i);
            NodeList elements = event.getChildNodes();
            int id = -1;
            String query = "";

            for (int j = 0; j < elements.getLength(); j++) {
                Node element = elements.item(j);
                if (element == null)
                    continue;

                if (element.getNodeName().equals("id"))
                    id = Integer.parseInt(element.getTextContent());
                else if (element.getNodeName().equals("query"))
                    query = element.getTextContent();
            }
            queries.put(id, new FeatureVector(query, stopper));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return queries;
}

From source file:Main.java

/**
 * Will create a documentFragment of the replacingDocument, will import the
 * replacingDocument as a node of the replacedDocument, and then will
 * replace the replaceNode with the documentFragment of replacingDocument.
 * //from  ww w . j  a  va2s.  c om
 * @param replacedDocument
 *            The document which will have a node replace
 * @param replacingDocument
 *            The document that will replace a node
 * @param replacedNode
 *            The node in replacedDocument that will be replaced
 * @return The new version of replacedDocument will replacedNode replaced
 */
public static Node replaceNode(Document replacedDocument, Document replacingDocument, Node replacedNode) {

    // Create a documentFragment of the replacingDocument
    DocumentFragment docFrag = replacingDocument.createDocumentFragment();
    Element rootElement = replacingDocument.getDocumentElement();
    docFrag.appendChild(rootElement);

    // Import docFrag under the ownership of replacedDocument
    Node replacingNode = ((replacedDocument).importNode(docFrag, true));

    // In order to replace the node need to retrieve replacedNode's parent
    Node replaceNodeParent = replacedNode.getParentNode();
    replaceNodeParent.replaceChild(replacingNode, replacedNode);
    return replacedDocument;
}

From source file:Main.java

public static byte[] transform(Transformer transformer, Document useDocument) {
    byte[] returnData = new byte[0];
    try {// w  w  w  .j  av  a2s .  c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(useDocument.getDocumentElement());
        transformer.transform(domSource, new StreamResult(baos));

        returnData = baos.toByteArray();

        baos.close();
    } catch (TransformerException te) {
        String err = new String(te.toString());
        returnData = err.getBytes();
        te.printStackTrace();
    } catch (IOException ie) {
        String err = new String(ie.toString());
        returnData = err.getBytes();
        ie.printStackTrace();
    }
    return returnData;
}

From source file:Main.java

public static String serializeDocumentToXml(Document document) {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    Element documentElement = document.getDocumentElement();
    serializeElement(sb, documentElement, 0);
    sb.append("\n");
    return sb.toString();
}

From source file:com.codebutler.farebot.card.Card.java

public static Card fromXml(String xml) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xml)));

    Element rootElement = doc.getDocumentElement();

    CardType type = CardType.class.getEnumConstants()[Integer.parseInt(rootElement.getAttribute("type"))];
    byte[] id = Utils.hexStringToByteArray(rootElement.getAttribute("id"));
    Date scannedAt = rootElement.hasAttribute("scanned_at")
            ? new Date(Long.valueOf(rootElement.getAttribute("scanned_at")))
            : new Date(0);
    switch (type) {
    case MifareDesfire:
        return DesfireCard.fromXml(id, scannedAt, rootElement);
    case CEPAS:/*from  w w  w .  j  a v  a 2  s  . c o m*/
        return CEPASCard.fromXML(id, scannedAt, rootElement);
    case FeliCa:
        return FelicaCard.fromXml(id, scannedAt, rootElement);
    case MifareClassic:
        return ClassicCard.fromXml(id, scannedAt, rootElement);
    default:
        throw new UnsupportedOperationException("Unsupported card type: " + type);
    }
}

From source file:com.google.enterprise.connector.importexport.ImportExport.java

/**
 * Reads a list of connectors from an XML file.
 *
 * @param filename source XML file for connectors.
 * @return an ImportExportConnectorList//  www. j  a  va  2  s  .c o m
 */
public static ImportExportConnectorList readFromFile(String filename) throws IOException {
    String xmlString = StringUtils.streamToStringAndThrow(new FileInputStream(filename));
    Document document = XmlParseUtil.parse(xmlString, new SAXParseErrorHandler(), null);
    Element connectorsElement = document.getDocumentElement();
    ImportExportConnectorList connectors = new ImportExportConnectorList();
    connectors.fromXml(document.getDocumentElement(), LegacyImportExportConnector.class);
    return connectors;
}

From source file:Main.java

public static String xmlToString(Document doc) throws Exception {

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc.getDocumentElement()), new StreamResult(writer));
    String result = writer.toString();
    System.out.println(result);/*from   w w w  .  ja va2s .c  o  m*/
    return result;
}

From source file:cz.incad.cdk.RepairVCProcess.java

public static void checkRelsExt(String pid, Document relsExt, FedoraAccess fa) {
    Element descElement = XMLUtils.findElement(relsExt.getDocumentElement(), "Description",
            FedoraNamespaces.RDF_NAMESPACE_URI);
    List<Element> delems = XMLUtils.getElements(descElement);
    for (Element rel : delems) {
        if (rel.getNamespaceURI() != null) {
            if (rel.getNamespaceURI().equals(FedoraNamespaces.RDF_NAMESPACE_URI)
                    && rel.getLocalName().equals("isMemberOfCollection")) {
                Attr resource = rel.getAttributeNodeNS(FedoraNamespaces.RDF_NAMESPACE_URI, "resource");
                if (resource != null) {
                    String value = resource.getValue();
                    if (value.startsWith(PIDParser.INFO_FEDORA_PREFIX)) {
                        try {
                            PIDParser pars = new PIDParser(value);
                            pars.disseminationURI();
                        } catch (LexerException e) {
                            LOGGER.log(Level.SEVERE, e.getMessage(), e);
                            //repair(pid, relsExt, fa, resource, value);
                        }//from   ww w  .  j  a  va  2  s  . co  m
                    } else {
                        repair(pid, relsExt, fa, resource, value);
                    }
                }
            }
        }
    }
}