Example usage for javax.xml.transform.dom DOMResult getNode

List of usage examples for javax.xml.transform.dom DOMResult getNode

Introduction

In this page you can find the example usage for javax.xml.transform.dom DOMResult getNode.

Prototype

public Node getNode() 

Source Link

Document

Get the node that will contain the result DOM tree.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
    xsr.nextTag(); // Advance to statements element

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
        DOMResult result = new DOMResult();
        t.transform(new StAXSource(xsr), result);
        Node domNode = result.getNode();
    }/*from   ww w .jav a 2 s  . com*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Main example = new Main();
    example.data.put("France", "Paris");
    example.data.put("Japan", "Tokyo");

    JAXBContext context = JAXBContext.newInstance(Main.class);
    Marshaller marshaller = context.createMarshaller();
    DOMResult result = new DOMResult();
    marshaller.marshal(example, result);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Document document = (Document) result.getNode();
    XPathExpression expression = xpath.compile("//map/entry");
    NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

    expression = xpath.compile("//map");
    Node oldMap = (Node) expression.evaluate(document, XPathConstants.NODE);
    Element newMap = document.createElement("map");

    for (int index = 0; index < nodes.getLength(); index++) {
        Element element = (Element) nodes.item(index);
        newMap.setAttribute(element.getAttribute("key"), element.getAttribute("value"));
    }/*from  w w  w  . j  a v a 2s . co m*/

    expression = xpath.compile("//map/..");
    Node parent = (Node) expression.evaluate(document, XPathConstants.NODE);
    parent.replaceChild(newMap, oldMap);

    TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document),
            new StreamResult(System.out));
}

From source file:com.semsaas.jsonxml.tools.JsonXpath.java

public static void main(String[] args) {
    /*//from   www  .j a v a 2 s . c  o m
     * Process options
     */
    LinkedList<String> files = new LinkedList<String>();
    LinkedList<String> expr = new LinkedList<String>();
    boolean help = false;
    String activeOption = null;
    String error = null;

    for (int i = 0; i < args.length && error == null && !help; i++) {
        if (activeOption != null) {
            if (activeOption.equals("-e")) {
                expr.push(args[i]);
            } else if (activeOption.equals("-h")) {
                help = true;
            } else {
                error = "Unknown option " + activeOption;
            }
            activeOption = null;
        } else {
            if (args[i].startsWith("-")) {
                activeOption = args[i];
            } else {
                files.push(args[i]);
            }
        }
    }

    if (error != null) {
        System.err.println(error);
        showHelp();
    } else if (help) {
        showHelp();
    } else {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            for (String f : files) {
                System.out.println("*** " + f + " ***");
                try {
                    // Create a JSON XML reader
                    XMLReader reader = XMLReaderFactory.createXMLReader("com.semsaas.jsonxml.JsonXMLReader");

                    // Prepare a reader with the JSON file as input
                    InputStreamReader stringReader = new InputStreamReader(new FileInputStream(f));
                    SAXSource saxSource = new SAXSource(reader, new InputSource(stringReader));

                    // Prepare a DOMResult which will hold the DOM of the xjson
                    DOMResult domResult = new DOMResult();

                    // Run SAX processing through a transformer
                    // (This could be done more simply, but we have here the opportunity to pass our xjson through
                    // an XSLT and get a legacy XML output ;) )
                    transformer.transform(saxSource, domResult);
                    Node dom = domResult.getNode();

                    XPathFactory xpathFactory = XPathFactory.newInstance();
                    for (String x : expr) {
                        try {
                            XPath xpath = xpathFactory.newXPath();
                            xpath.setNamespaceContext(new NamespaceContext() {
                                public Iterator getPrefixes(String namespaceURI) {
                                    return null;
                                }

                                public String getPrefix(String namespaceURI) {
                                    return null;
                                }

                                public String getNamespaceURI(String prefix) {
                                    if (prefix == null) {
                                        return XJSON.XMLNS;
                                    } else if ("j".equals(prefix)) {
                                        return XJSON.XMLNS;
                                    } else {
                                        return null;
                                    }
                                }
                            });
                            NodeList nl = (NodeList) xpath.evaluate(x, dom, XPathConstants.NODESET);
                            System.out.println("-- Found " + nl.getLength() + " nodes for xpath '" + x
                                    + "' in file '" + f + "'");
                            for (int i = 0; i < nl.getLength(); i++) {
                                System.out.println(" +(" + i + ")+ ");
                                XMLJsonGenerator handler = new XMLJsonGenerator();
                                StringWriter buffer = new StringWriter();
                                handler.setOutputWriter(buffer);

                                SAXResult result = new SAXResult(handler);
                                transformer.transform(new DOMSource(nl.item(i)), result);

                                System.out.println(buffer.toString());
                            }
                        } catch (XPathExpressionException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        } catch (TransformerException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        }
                    }
                } catch (FileNotFoundException e) {
                    System.err.println("File '" + f + "' was not found");
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:DOM2DOM.java

public static void main(String[] args) throws TransformerException, TransformerConfigurationException,
        FileNotFoundException, ParserConfigurationException, SAXException, IOException {
    TransformerFactory tFactory = TransformerFactory.newInstance();

    if (tFactory.getFeature(DOMSource.FEATURE) && tFactory.getFeature(DOMResult.FEATURE)) {
        //Instantiate a DocumentBuilderFactory.
        DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();

        // And setNamespaceAware, which is required when parsing xsl files
        dFactory.setNamespaceAware(true);

        //Use the DocumentBuilderFactory to create a DocumentBuilder.
        DocumentBuilder dBuilder = dFactory.newDocumentBuilder();

        //Use the DocumentBuilder to parse the XSL stylesheet.
        Document xslDoc = dBuilder.parse("birds.xsl");

        // Use the DOM Document to define a DOMSource object.
        DOMSource xslDomSource = new DOMSource(xslDoc);

        // Set the systemId: note this is actually a URL, not a local filename
        xslDomSource.setSystemId("birds.xsl");

        // Process the stylesheet DOMSource and generate a Transformer.
        Transformer transformer = tFactory.newTransformer(xslDomSource);

        //Use the DocumentBuilder to parse the XML input.
        Document xmlDoc = dBuilder.parse("birds.xml");

        // Use the DOM Document to define a DOMSource object.
        DOMSource xmlDomSource = new DOMSource(xmlDoc);

        // Set the base URI for the DOMSource so any relative URIs it contains can
        // be resolved.
        xmlDomSource.setSystemId("birds.xml");

        // Create an empty DOMResult for the Result.
        DOMResult domResult = new DOMResult();

        // Perform the transformation, placing the output in the DOMResult.
        transformer.transform(xmlDomSource, domResult);

        //Instantiate an Xalan XML serializer and use it to serialize the output DOM to System.out
        // using the default output format, except for indent="yes"
        java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
        xmlProps.setProperty("indent", "yes");
        xmlProps.setProperty("standalone", "no");
        Serializer serializer = SerializerFactory.getSerializer(xmlProps);
        serializer.setOutputStream(System.out);
        serializer.asDOMSerializer().serialize(domResult.getNode());
    } else {/*from   w ww .j ava 2s .  co  m*/
        throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!");
    }
}

From source file:Main.java

public static Node bytesToXml(final byte[] body) throws TransformerException {
    final Transformer transformer = FACTORY.newTransformer();
    final Source source = new StreamSource(new ByteArrayInputStream(body));
    final DOMResult result = new DOMResult();
    transformer.transform(source, result);
    return result.getNode();
}

From source file:Main.java

public static Node transform(String xslSource, Node original) {
    StringReader sr = new StringReader(xslSource);
    DOMResult result = new DOMResult();
    doTransform(new StreamSource(sr), new DOMSource(original), result);
    return result.getNode();
}

From source file:Main.java

public static Node applyXslToDocument2(Source xslt, Source doc, URIResolver resolver,
        Properties transformerProperties, HashMap<String, String> params, String transformerClassName)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException,
        NoSuchMethodException, TransformerConfigurationException, TransformerException {
    TransformerFactory transformerFactory = null;
    if (transformerClassName == null)
        transformerFactory = TransformerFactory.newInstance();
    else {//  w w w. j a  v a 2  s  . c om
        Class transformerClass = Class.forName(transformerClassName);
        Constructor defaultConstructor = transformerClass.getConstructor(null);
        transformerFactory = (TransformerFactory) transformerClass.newInstance();
    }

    if (resolver != null)
        transformerFactory.setURIResolver(resolver);

    Transformer transformer = transformerFactory.newTransformer(xslt);
    if (transformerFactory != null)
        transformer.setOutputProperties(transformerProperties);

    if (params != null) {
        for (Map.Entry<String, String> cursor : params.entrySet()) {
            transformer.setParameter(cursor.getKey(), cursor.getValue());
        }
    }

    DOMResult result = new DOMResult();
    transformer.transform(doc, result);

    return (result.getNode());
}

From source file:Main.java

/**
 * General method for transformation to a DOM Document. Transform a Source
 * document using a Source XSL document and an array of parameters.
 * The parameter array consists of a sequence of pairs of (String parametername)
 * followed by (Object parametervalue) in an Object[].
 * @param doc the XML document to transform.
 * @param xsl the XSL transformation program.
 * @param params the array of transformation parameters.
 * @return the transformed text./*w  w  w  .  ja v a  2 s  .  c o  m*/
 */
public static Document getTransformedDocument(Source doc, Source xsl, Object[] params) throws Exception {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xsl);
    if ((params != null) && (params.length > 1)) {
        for (int i = 0; i < params.length; i = i + 2) {
            transformer.setParameter((String) params[i], params[i + 1]);
        }
    }
    DOMResult domResult = new DOMResult();
    transformer.transform(doc, domResult);
    return (Document) domResult.getNode();
}

From source file:Main.java

/**
 * Clones a document object./*w  w w  . j av a2  s .  c  om*/
 *
 * @param doc The document to be cloned.
 * @return The new document object that contains the same data as the original document.
 * @throws TransformerException Thrown if the document can't be
 */
public static Document cloneDocument(final Document doc) throws TransformerException {
    final Node rootNode = doc.getDocumentElement();

    // Copy the doctype and xml version type data
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    final Transformer tx = tfactory.newTransformer();
    final DOMSource source = new DOMSource(doc);
    final DOMResult result = new DOMResult();
    tx.transform(source, result);

    // Copy the actual content into the new document
    final Document copy = (Document) result.getNode();
    copy.removeChild(copy.getDocumentElement());
    final Node copyRootNode = copy.importNode(rootNode, true);
    copy.appendChild(copyRootNode);

    return copy;
}

From source file:net.javacrumbs.smock.common.XmlUtil.java

/**
 * Loads document from source./*from  w ww  .  j av a2 s  . co m*/
 * @param source
 * @return
 */
public static Document loadDocument(Source source) {
    DOMResult result = new DOMResult();
    transform(source, result);
    return (Document) result.getNode();
}