Example usage for org.w3c.dom Document createElement

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

Introduction

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

Prototype

public Element createElement(String tagName) throws DOMException;

Source Link

Document

Creates an element of the type specified.

Usage

From source file:Main.java

public static boolean creteEntity(Object entity, String fileName) {
    boolean flag = false;
    try {/*from  w  w  w  .ja v  a2 s  .  c  om*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(fileName);

        Class clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Node EntityElement = document.getElementsByTagName(clazz.getSimpleName() + "s").item(0);

        Element newEntity = document.createElement(clazz.getSimpleName());
        EntityElement.appendChild(newEntity);

        for (Field field : fields) {
            field.setAccessible(true);
            Element element = document.createElement(field.getName());
            element.appendChild(document.createTextNode(field.get(entity).toString()));
            newEntity.appendChild(element);
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(fileName));
        transformer.transform(domSource, streamResult);
        flag = true;
    } catch (ParserConfigurationException pce) {
        System.out.println(pce.getLocalizedMessage());
        pce.printStackTrace();
    } catch (TransformerException te) {
        System.out.println(te.getLocalizedMessage());
        te.printStackTrace();
    } catch (IOException ioe) {
        System.out.println(ioe.getLocalizedMessage());
        ioe.printStackTrace();
    } catch (SAXException sae) {
        System.out.println(sae.getLocalizedMessage());
        sae.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return flag;
}

From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java

/**
 * Extracts sentence nodes from a POS-tagger XML document.  These sentences are intended to provide some notion of
 * locality for identified chemical entities.
 *
 * @param docBuilder A document builder to use when producing single-sentence XML documents.
 * @param doc        The POS-tagger XML document from which to extract sentences.
 * @return A list of single-sentence documents.
 * @throws ParserConfigurationException//from   w w  w .j a v  a 2  s. c  om
 * @throws XPathExpressionException
 */
private static List<Document> findSentences(DocumentBuilder docBuilder, Document doc)
        throws ParserConfigurationException, XPathExpressionException {
    if (doc != null) {
        // TODO: is there a more efficient yet still safe way to do this?
        XPath xpath = Util.getXPathFactory().newXPath();
        // TODO: get rid of this inline xpath compilation, run during setup.
        NodeList nodes = (NodeList) xpath.evaluate(SENTENCE_PATH, doc, XPathConstants.NODESET);

        List<Document> docList = new ArrayList<>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);

            /* With help from:
             * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */
            org.w3c.dom.Document newDoc = docBuilder.newDocument();
            Element rootElement = newDoc.createElement(SENTENCE_DOC_HEADER);
            Node newNode = newDoc.importNode(n, true);
            rootElement.appendChild(newNode);
            newDoc.appendChild(rootElement);
            docList.add(newDoc);
        }
        return docList;
    } else {
        // TODO: log here.
        return new ArrayList<>(0);
    }
}

From source file:com.viettel.ws.client.JDBCUtil.java

public static Element createRowElement(Object obj, Document doc) {
    Element row = doc.createElement("Row");
    Class cls = obj.getClass();/*from  w  w  w  .  jav a 2 s .  c o  m*/
    Field[] fieldArr = cls.getDeclaredFields();
    SimpleDateFormat fm = new SimpleDateFormat("dd/MM/yyyy");

    for (int i = 0; i < fieldArr.length; i++) {
        try {
            String fieldName = fieldArr[i].getName();
            String getMethodName = "get" + UpcaseFirst(fieldName);
            Method getMethod = cls.getMethod(getMethodName);

            Object value = getMethod.invoke(obj);
            if (fieldArr[i].getType().equals(Date.class)) {
                value = fm.format(value);
            }

            Element node = doc.createElement(convertToOrigin(fieldName));
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);

        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            continue;
        }
    }
    return row;
}

From source file:es.itecban.deployment.security.client.ws.LogonWS.java

private static void addTextNode(Element element, String nodeName, String textValue) {
    // Get the document
    Document doc = element.getOwnerDocument();
    // Write the name
    Node resourceNameNode = doc.createElement(nodeName);
    element.appendChild(resourceNameNode);
    Text resourceNameText = doc.createTextNode(textValue);
    resourceNameNode.appendChild(resourceNameText);
}

From source file:edu.cmu.cs.lti.ark.fn.evaluation.PrepareFullAnnotationXML.java

public static Element buildAnnotationSet(String frame, List<DataPointWithFrameElements> dataPointList,
        Document doc, int parentId, int num) {
    final Element ret = doc.createElement("annotationSet");
    final int setId = parentId * 100 + num;
    addAttribute(doc, "ID", ret, "" + setId);
    addAttribute(doc, "frameName", ret, frame);

    final Element layers = doc.createElement("layers");

    // Target Layer
    final Element targetLayer = doc.createElement("layer");
    final int layerId1 = setId * 100 + 1;
    addAttribute(doc, "ID", targetLayer, "" + layerId1);
    addAttribute(doc, "name", targetLayer, "Target");
    final Element targetLabels = doc.createElement("labels");
    // Target info is inlined in every data point; might as well look at the first one
    final DataPointWithFrameElements firstDataPoint = dataPointList.get(0);
    final List<Range0Based> targetTokenRanges = firstDataPoint.getTokenStartEnds(true);
    final List<Range0Based> targetCharRanges = firstDataPoint.getCharStartEnds(targetTokenRanges);
    int count = 0;
    for (int i : xrange(targetCharRanges.size())) {
        final Range0Based charRange = targetCharRanges.get(i);
        final Range0Based tokenRange = targetTokenRanges.get(i);
        final int labelId1 = layerId1 * 100 + count + 1;
        final Element label1 = doc.createElement("label");
        addAttribute(doc, "ID", label1, "" + labelId1);
        addAttribute(doc, "name", label1, "Target");
        addAttribute(doc, "start", label1, "" + charRange.start);
        addAttribute(doc, "end", label1, "" + charRange.end);
        addAttribute(doc, "tokenStart", label1, "" + tokenRange.start);
        addAttribute(doc, "tokenEnd", label1, "" + tokenRange.end);
        targetLabels.appendChild(label1);
        count = count + 3;/*  www .j a  v  a  2 s  . c om*/
    }
    targetLayer.appendChild(targetLabels);
    layers.appendChild(targetLayer);

    // Frame Element Layers
    for (DataPointWithFrameElements dataPointWithFrameElements : dataPointList) {
        final int rank = dataPointWithFrameElements.rank;
        final double score = dataPointWithFrameElements.score;
        final Element feLayer = doc.createElement("layer");
        final int layerId = setId * 100 + rank + 1;
        addAttribute(doc, "ID", feLayer, "" + layerId);
        addAttribute(doc, "name", feLayer, "FE");
        addAttribute(doc, "kbestRank", feLayer, "" + rank);
        addAttribute(doc, "score", feLayer, "" + score);
        layers.appendChild(feLayer);

        final Element labels = doc.createElement("labels");
        feLayer.appendChild(labels);

        final List<Range0Based> fillerSpans = dataPointWithFrameElements.getOvertFrameElementFillerSpans();
        final List<String> feNames = dataPointWithFrameElements.getOvertFilledFrameElementNames();
        for (int i = 0; i < feNames.size(); i++) {
            final String feName = feNames.get(i);
            final Range fillerSpan = fillerSpans.get(i);

            final int labelId = layerId * 100 + i + 1;
            final Element label = doc.createElement("label");
            addAttribute(doc, "ID", label, "" + labelId);
            addAttribute(doc, "name", label, feName);

            final int tokenStart = fillerSpan.start;
            final int tokenEnd = fillerSpan.end;
            final int startCharIndex = dataPointWithFrameElements.getCharacterIndicesForToken(tokenStart).start;
            final int endCharIndex = dataPointWithFrameElements.getCharacterIndicesForToken(tokenEnd).end;
            addAttribute(doc, "start", label, "" + startCharIndex);
            addAttribute(doc, "end", label, "" + endCharIndex);
            addAttribute(doc, "tokenStart", label, "" + tokenStart);
            addAttribute(doc, "tokenEnd", label, "" + tokenEnd);
            labels.appendChild(label);
        }
    }
    ret.appendChild(layers);
    return ret;
}

From source file:edu.cudenver.bios.matrixsvc.representation.CholeskyDecompositionXmlRepresentation.java

static Element createXml(CholeskyDecompositionImpl _cdImpl, Document _doc) {
    NamedRealMatrix L = new NamedRealMatrix(_cdImpl.getL());
    NamedRealMatrix LT = new NamedRealMatrix(_cdImpl.getLT());
    L.setName(MatrixConstants.SQ_ROOT_MATRIX_RETURN_NAME);
    LT.setName(MatrixConstants.TRANSPOSE_MATRIX_RETURN_NAME);
    Element rootElem = _doc.createElement(MatrixConstants.TAG_CHOLESKY_DECOMP);

    //Get XML for first matrix
    logger.debug("Calling MatrixXmlRepresentation.createMatrixNodeFromRealMatrix() " + "for L matrix.");
    Node matrixL = MatrixXmlRepresentation.createMatrixNodeFromRealMatrix(L, _doc);

    //Get XML for second matrix
    logger.debug("Calling MatrixXmlRepresentation.createMatrixNodeFromRealMatrix() " + "for LT matrix.");
    Node matrixLT = MatrixXmlRepresentation.createMatrixNodeFromRealMatrix(LT, _doc);

    //Add our matrices to our root element
    rootElem.appendChild(matrixL);/*www .j a v a 2 s .c o m*/
    rootElem.appendChild(matrixLT);

    return rootElem;
}

From source file:no.kantega.commons.util.XMLHelper.java

public static Element setChild(Document doc, Document parent, String name) {
    Element child = doc.getDocumentElement();
    if (child == null) {
        child = doc.createElement(name);
        parent.appendChild(child);//  w  ww  .  j a v  a 2s  .c o m
    }
    return child;
}

From source file:Main.java

public static Node cloneNode(Document d, Node n) {
    Node r = null;//w  w  w  .j av a2  s .co  m
    switch (n.getNodeType()) {
    case Node.TEXT_NODE:
        r = d.createTextNode(((Text) n).getData());
        break;
    case Node.CDATA_SECTION_NODE:
        r = d.createCDATASection(((CDATASection) n).getData());
        break;
    case Node.ELEMENT_NODE:
        r = d.createElement(((Element) n).getTagName());
        NamedNodeMap map = n.getAttributes();
        for (int i = 0; i < map.getLength(); i++) {
            ((Element) r).setAttribute(((Attr) map.item(i)).getName(), ((Attr) map.item(i)).getValue());
        }
        break;
    }
    return r;
}

From source file:com.aurel.track.exchange.docx.exporter.CustomXML.java

/**
 * Creates a dom element//  w  w  w  . j a v  a 2  s .  c o  m
 * @param elementName
 * @param elementValue
 * @param dom
 * @return
 */
private static Element createDomElement(String elementName, String elementValue, Document dom) {
    Element element = null;
    try {
        try {
            element = dom.createElement(elementName);
        } catch (DOMException e) {
            LOGGER.warn("Creating an XML node with the element name " + elementName
                    + " failed with dom exception " + e);
        }
        if (element == null) {
            return null;
        }
        if (elementValue == null || "".equals(elementValue.trim())) {
            element.appendChild(dom.createTextNode(""));
        } else {
            try {
                element.appendChild(dom.createTextNode(Html2Text.stripNonValidXMLCharacters(elementValue)));
            } catch (DOMException e) {
                LOGGER.info("Creating the node for text element " + elementName + " and the value "
                        + elementValue + " failed with dom exception " + e);
                element.appendChild(dom.createTextNode(""));
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Creating an XML node with the element name " + elementName + " failed with " + e);
    }
    return element;
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create Empty Document//from  w w w.  j  ava 2  s.  c  o m
 *
 * @return A empty document
 * @throws ParserConfigurationException - If error when create document
 */
public static Document createDocument() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);
    return doc;
}