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: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   w  w  w  .j a  v a2s.  com
    }
    project.appendChild(itemGroup);
}

From source file:com.google.visualization.datasource.render.HtmlRenderer.java

/**
 * Appends a simple text line to the body of the document.
 *
 * @param document The containing document.
 * @param bodyElement The body of the document.
 * @param text The text to append./*from  w  w  w  .ja v  a2 s  .c  o  m*/
 */
private static void appendSimpleText(Document document, Element bodyElement, String text) {
    Element statusElement = document.createElement("div");
    statusElement.setTextContent(text);
    bodyElement.appendChild(statusElement);
}

From source file:Main.java

/**
 * Same as {@link createChild(Node, String) createChild()}, but adds the
 * specified <code>text</code> to the newly created <code>Node</code>.
 * /*from  w  ww .  jav  a  2s  .c  o m*/
 * @see #createChild(Node, String)
 * @param elem the <code>Node</code> to which the newly created 
 * <code>Node</code> will be appended to. Not allowed to be <code>null</code>.
 * @param elemName the name of the to-be-created <code>Node</code>, not allowed 
 * to be empty or <code>null</code>.
 * @param text the text-contents of the created/inserted node  
 * @return the created element
 * @exception IllegalArgumentException if <code>elem</code> and/ord
 * <code>elemName</code> are null (or empty in the case of <code>elemName</code>)
 */
public static Element createTextChild(Node node, String elemName, String text) {
    if (node == null || elemName == null || "".equals(elemName))
        throw new IllegalArgumentException("Arguments are not allowed to be null or empty");

    Document document = null;

    if (node instanceof Document) {
        document = (Document) node;
    } else if (node.getOwnerDocument() != null) {
        document = node.getOwnerDocument();
    }

    Element newChild = null;
    if (document != null) {
        newChild = document.createElement(elemName);
        node.appendChild(newChild);
        newChild.appendChild(document.createTextNode(text));
    }

    return newChild;
}

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

/**
 * Create document using DOM api/*from   w  w  w .  j ava2s .c  o  m*/
 *
 * @param rs a result set
 * @return A document of a result set
 * @throws ParserConfigurationException - If error when parse string
 * @throws SQLException - If error when read data from database
 */
public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException {
    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);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    return doc;
}

From source file:Main.java

public static void vectorToXML222(String xmlFile, String xpath, String parentNodeName, Vector<HashMap> vector) {
    File file = new File(xmlFile);
    try {//from  w w w.  ja  v a 2 s . com
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document document;
        Element rootNode;
        if (file.exists()) {
            document = documentBuilder.parse(new File(xmlFile));
            rootNode = document.getDocumentElement();
        } else {
            document = documentBuilder.newDocument();
            rootNode = document.createElement(xpath);
            document.appendChild(rootNode);
        }

        for (int x = 0; x < vector.size(); x++) {
            Element parentNode = document.createElement(parentNodeName);
            rootNode.appendChild(parentNode);
            HashMap hashmap = vector.get(x);
            Set set = hashmap.entrySet();
            Iterator i = set.iterator();

            while (i.hasNext()) {
                Map.Entry me = (Map.Entry) i.next();
                // System.out.println("key=" +
                // me.getKey().toString());
                Element em = document.createElement(me.getKey().toString());
                em.appendChild(document.createTextNode(me.getValue().toString()));
                parentNode.appendChild(em);
                // System.out.println("write " +
                // me.getKey().toString() +
                // "="
                // + me.getValue().toString());
            }
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        FileOutputStream fo = new FileOutputStream(xmlFile);
        StreamResult result = new StreamResult(fo);
        transformer.transform(source, result);
    } catch (Exception ex) {
        file.delete();
        ex.printStackTrace();
    }
}

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

public static Element setChildText(Document doc, Element parent, String name, String value) {
    Element child = getChildByName(parent, name);
    if (child == null) {
        child = doc.createElement(name);
        child.appendChild(doc.createTextNode(value == null ? "" : value));
        parent.appendChild(child);/* www .java 2  s.  com*/
    } else {
        Node text = child.getFirstChild();
        if (text != null) {
            text.setNodeValue(value);
        } else {
            child.appendChild(doc.createTextNode(value == null ? "" : value));
        }
    }
    return child;
}

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

/**
 * Given several parallel lists of predicted frame instances, including their frame elements, create an XML file 
 * for the full-text annotation predicted by the model.
 * @param predictedFELines Lines encoding predicted frames & FEs in the same format as the .sentences.frame.elements files
 * @param sentenceNums Global sentence number for the first sentence being predicted, so as to map FE lines to items in parses/orgLines
 * @param parses Lines encoding the parse for each sentence
 * @param origLines The original sentences, untokenized
 * @return/*from ww w.j  a v a2 s .c om*/
 */
public static Document createXMLDoc(List<String> predictedFELines, Range sentenceNums, List<String> parses,
        List<String> origLines) {
    final Document doc = XmlUtils.getNewDocument();
    final Element corpus = doc.createElement("corpus");
    addAttribute(doc, "ID", corpus, "100");
    addAttribute(doc, "name", corpus, "ONE");
    addAttribute(doc, "XMLCreated", corpus, new Date().toString());
    final Element documents = doc.createElement("documents");
    corpus.appendChild(documents);

    final Element document = doc.createElement("document");
    addAttribute(doc, "ID", document, "1");
    addAttribute(doc, "description", document, "TWO");
    documents.appendChild(document);

    final Element paragraphs = doc.createElement("paragraphs");
    document.appendChild(paragraphs);

    final Element paragraph = doc.createElement("paragraph");
    addAttribute(doc, "ID", paragraph, "2");
    addAttribute(doc, "documentOrder", paragraph, "1");
    paragraphs.appendChild(paragraph);

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

    // Map sentence offsets to frame annotation data points within each sentence
    final TIntObjectHashMap<Set<String>> predictions = new TIntObjectHashMap<Set<String>>();
    for (String feLine : predictedFELines) {
        final int sentNum = DataPointWithFrameElements.parseFrameNameAndSentenceNum(feLine).second;

        if (!predictions.containsKey(sentNum))
            predictions.put(sentNum, new THashSet<String>());

        predictions.get(sentNum).add(feLine);
    }

    for (int sent = sentenceNums.start; sent < sentenceNums.start + sentenceNums.length(); sent++) {
        final String parseLine = parses.get(sent - sentenceNums.start);

        final Element sentence = doc.createElement("sentence");
        addAttribute(doc, "ID", sentence, "" + (sent - sentenceNums.start));

        final Element text = doc.createElement("text");
        final String origLine = origLines.get(sent - sentenceNums.start);
        final Node textNode = doc.createTextNode(origLine);
        text.appendChild(textNode);
        sentence.appendChild(text);
        final Element tokensElt = doc.createElement("tokens");
        final String[] tokens = origLine.trim().split(" ");
        for (int i : xrange(tokens.length)) {
            final String token = tokens[i];
            final Element tokenElt = doc.createElement("token");
            addAttribute(doc, "index", tokenElt, "" + i);
            final Node tokenNode = doc.createTextNode(token);
            tokenElt.appendChild(tokenNode);
            tokensElt.appendChild(tokenElt);
        }
        sentence.appendChild(tokensElt);

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

        int frameIndex = 0; // index of the predicted frame within the sentence
        final Set<String> feLines = predictions.get(sent);

        if (feLines != null) {
            final List<DataPointWithFrameElements> dataPoints = Lists.newArrayList();
            for (String feLine : feLines) {
                final DataPointWithFrameElements dp = new DataPointWithFrameElements(parseLine, feLine);
                dp.processOrgLine(origLine);
                dataPoints.add(dp);
            }
            final Set<String> seenTargetSpans = Sets.newHashSet();
            for (DataPointWithFrameElements dp : dataPoints) {
                final String targetIdxsString = Arrays.toString(dp.getTargetTokenIdxs());
                if (seenTargetSpans.contains(targetIdxsString)) {
                    System.err.println("Duplicate target tokens: " + targetIdxsString
                            + ". Skipping. Sentence id: " + sent);
                    continue; // same target tokens should never show up twice in the same sentence
                } else {
                    seenTargetSpans.add(targetIdxsString);
                }
                assert dp.rank == 1; // this doesn't work with k-best lists anymore
                final String frame = dp.getFrameName();
                // Create the <annotationSet> Element for the predicted frame annotation, and add it under the sentence
                Element annotationSet = buildAnnotationSet(frame, ImmutableList.of(dp), doc,
                        sent - sentenceNums.start, frameIndex);
                annotationSets.appendChild(annotationSet);
                frameIndex++;
            }
        }
        sentence.appendChild(annotationSets);
        sentences.appendChild(sentence);
    }
    paragraph.appendChild(sentences);
    doc.appendChild(corpus);
    return doc;
}

From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

private static void addEvent(Document document, Node sessionFactoryElement, String eventType,
        String listenerClass) {/*from ww  w .jav  a2 s. c  o  m*/
    Element event = document.createElement("event"); //$NON-NLS-1$
    Attr type = document.createAttribute("type"); //$NON-NLS-1$
    type.setValue(eventType);
    event.getAttributes().setNamedItem(type);
    {
        Element listener = document.createElement("listener"); //$NON-NLS-1$
        Attr clazz = document.createAttribute("class"); //$NON-NLS-1$
        clazz.setValue(listenerClass);
        listener.getAttributes().setNamedItem(clazz);
        event.appendChild(listener);
    }
    sessionFactoryElement.appendChild(event);
}

From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

private static void addProperty(Document document, Node sessionFactoryElement, String propertyName,
        String propertyValue) {/*from  w ww  . ja  v  a2  s  . co m*/
    Element property = document.createElement("property"); //$NON-NLS-1$
    Attr name = document.createAttribute("name"); //$NON-NLS-1$
    name.setValue(propertyName);
    property.getAttributes().setNamedItem(name);
    property.appendChild(document.createTextNode(propertyValue));
    sessionFactoryElement.appendChild(property);
}

From source file:be.fedict.eid.dss.ws.DSSUtil.java

public static Element getStorageInfoElement(StorageInfo storageInfo) {

    Document newDocument = documentBuilder.newDocument();
    Element newElement = newDocument.createElement("newNode");
    try {//from  w  w  w.j  a  v a 2  s.c o  m
        artifactMarshaller.marshal(artifactObjectFactory.createStorageInfo(storageInfo), newElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
    return (Element) newElement.getFirstChild();
}