Example usage for org.w3c.dom Document appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);//from w w  w .j a v a  2  s.c o m
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    element = doc.createElement("root");
    doc.appendChild(element);

    Comment comment = doc.createComment("a comment");
    doc.insertBefore(comment, element);

}

From source file:Main.java

public static void main(String argv[]) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);

    // staff elements
    Element staff = doc.createElement("Staff");
    rootElement.appendChild(staff);/*w w w .j  a v  a2  s .  com*/

    // set attribute to staff element
    Attr attr = doc.createAttribute("id");
    attr.setValue("1");
    staff.setAttributeNode(attr);

    // shorten way
    // staff.setAttribute("id", "1");

    // firstname elements
    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("A"));
    staff.appendChild(firstname);

    // lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("B"));
    staff.appendChild(lastname);

    // nickname elements
    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("C"));
    staff.appendChild(nickname);

    // salary elements
    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("100000"));
    staff.appendChild(salary);

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("C:\\file.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String exp = "/configs/markets/market";
    String path = "data.xml";

    Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(exp);
    NodeList nodes = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);

    Document newXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = newXmlDocument.createElement("root");
    newXmlDocument.appendChild(root);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Node copyNode = newXmlDocument.importNode(node, true);
        root.appendChild(copyNode);//  ww w  .ja v a  2  s.  c  o m
    }
    printXmlDocument(newXmlDocument);
}

From source file:MainClass.java

public static void main(String args[]) {
    Document dom = DOMImplementation.createDocument(null, null, null);
    Element root = dom.createElement("games");
    Element child1 = dom.createElement("game");
    root.appendChild(child1);/*ww w.java 2  s  . com*/
    dom.appendChild(root);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
    dFactory.setValidating(false);/*from  w  ww. j a v a2  s.  c om*/
    DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
    Document dDoc = dBuilder.newDocument();

    // The root document element. 
    Element pageDataElement = dDoc.createElement("page-data");
    pageDataElement.appendChild(dDoc.createTextNode("Example Text."));

    dDoc.appendChild(pageDataElement);

    System.out.println(dDoc.getDocumentElement().getTextContent());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // Create a new document
    Document xmlDoc = builder.newDocument();
    // Create root node for the document...
    Element root = xmlDoc.createElement("Players");
    xmlDoc.appendChild(root);

    // Create a "player" node
    Element player = xmlDoc.createElement("player");
    // Set the players ID attribute
    player.setAttribute("ID", "1");

    // Create currentRank node...
    Element currentRank = xmlDoc.createElement("currentRank");
    currentRank.setTextContent("1");
    player.appendChild(currentRank);/*from   w  w  w.j  a v a  2s  .  com*/

    // Create previousRank node...
    Element previousRank = xmlDoc.createElement("previousRank");
    previousRank.setTextContent("1");
    player.appendChild(previousRank);

    // Create playerName node...
    Element playerName = xmlDoc.createElement("PlayerName");
    playerName.setTextContent("Max");
    player.appendChild(playerName);

    // Create Money node...
    Element money = xmlDoc.createElement("Money");
    money.setTextContent("15");
    player.appendChild(money);

    // Add the player to the root node...
    root.appendChild(player);

    ByteArrayOutputStream baos = null;

    baos = new ByteArrayOutputStream();

    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.setOutputProperty(OutputKeys.METHOD, "xml");
    tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    DOMSource domSource = new DOMSource(xmlDoc);
    StreamResult sr = new StreamResult(baos);
    tf.transform(domSource, sr);

    baos.flush();
    System.out.println(new String(baos.toByteArray()));
    baos.close();

}

From source file:Main.java

public static void main(String[] args) throws Throwable {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*w w w  .j a v a  2 s .c o  m*/

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element root = doc.createElement("root");
    root.setAttribute("xmlns:m", "http://www.java2s.com/blog");
    root.setAttribute("xmlns:rt", "http://www.java2s.com/forum");
    doc.appendChild(root);

    Element elt = doc.createElement("simple");
    elt.setAttribute("m:Path", "false");
    elt.setAttribute("m:Content", "false");
    elt.setAttribute("rt:file", "false");

    root.appendChild(doc.createTextNode("\n\t"));
    root.appendChild(elt);
    root.appendChild(doc.createTextNode("\n"));
    TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc),
            new StreamResult(System.out));
}

From source file:MainClass.java

public static void main(String args[]) throws IOException {
    Document dom = DOMImplementation.createDocument(null, null, null);

    Element root = dom.createElement("A");

    Element child1 = dom.createElement("B");

    child1.appendChild(dom.createTextNode("C"));

    child1.setAttribute("A", "a");

    root.appendChild(child1);/*from  ww  w . j a v  a2  s . c o  m*/

    dom.appendChild(root);

    XMLSerializer serial = new XMLSerializer(System.out, null);
    serial.serialize(dom.getDocumentElement());
}

From source file:TestSign.java

/**
 * Method main//w  w  w . j  a  va  2 s  .  c  om
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("signature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    doc.appendChild(sig.getElement());

    {
        ObjectContainer obj = new ObjectContainer(doc);
        Element anElement = doc.createElementNS(null, "InsideObject");

        anElement.appendChild(doc.createTextNode("A text in a box"));
        obj.appendChild(anElement);

        String Id = "TheFirstObject";

        obj.setId(Id);
        sig.appendObject(obj);

        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#" + Id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    for (int i = 0; i < sig.getSignedInfo().getSignedContentLength(); i++) {
        System.out.println("--- Signed Content follows ---");
        System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i)));
    }
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java

/**
 * Main (starting) method of the command line application.
 *
 * @param argv Array of command line arguments that are expected to be
 * filesystem paths to input XML documents with MathML to be unified.
 * @throws ParserConfigurationException If a XML DOM builder cannot be
 * created with the configuration requested.
 *//*  www.ja  v  a 2  s. com*/
public static void main(String argv[]) throws ParserConfigurationException {

    final Options options = new Options();
    options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes");
    options.addOption("h", "help", false, "print help");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }
        operatorUnification = line.hasOption('p');

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {

            Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument();
            Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM);
            outerDocument.appendChild(rootNode);

            for (String filepath : arguments) {
                try {

                    Document doc = DOMBuilder.buildDocFromFilepath(filepath);
                    MathMLUnificator.unifyMathML(doc, operatorUnification);
                    if (arguments.size() == 1) {
                        xmlStdoutSerializer(doc);
                    } else {
                        Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM);
                        Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":"
                                        + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR);
                        filenameAttr.setTextContent(String.valueOf(filepath));
                        ((Element) itemNode).setAttributeNodeNS(filenameAttr);
                        itemNode.appendChild(
                                rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true));
                        rootNode.appendChild(itemNode);

                    }

                } catch (SAXException | IOException ex) {
                    Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE,
                            "Failed processing of file: " + filepath, ex);
                }
            }

            if (rootNode.getChildNodes().getLength() > 0) {
                xmlStdoutSerializer(rootNode.getOwnerDocument());
            }

        } else {
            printHelp(options);
            System.exit(0);
        }
    }

}