Try a cloneNode followed by an adoptNode to use a child element as the root element of a new Document.
String xml = "<hello><world /></hello>";
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document0 = db.parse(new InputSource(new StringReader(xml)));
Document document1 = db.newDocument();
NodeList nodeList = document0.getDocumentElement().getChildNodes();
document1.appendChild(document1.adoptNode(nodeList.item(0).cloneNode(true)));
// Serialize the two documents to check that the copy was correct.
ByteArrayOutputStream output = new ByteArrayOutputStream();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document0), new StreamResult(output));
System.out.println(output.toString("UTF-8"));
output.reset();
transformer.transform(new DOMSource(document1), new StreamResult(output));
System.out.println(output.toString("UTF-8"));
} catch (TransformerException e) {
} catch (IOException e) {
} catch (SAXException e) {
} catch (ParserConfigurationException e) {
}
Answer from Jens on Stack OverflowWhat I did was basically follow the OP's answer, but I had beforehand to create the .jar file. To do so, I just prepared my custom class in test.java:
import java.lang.System;
public class Test {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
And then
javac Test.java
jar cf test.jar Test.class
Now you should see the .jar created. From this point, you are able to access it from Javascript:
let java= require('java');
java.classpath.push('test.jar');
let test = java.import("Test");
test.main(null) // should print "Hello, World!"
After a lot of trying, this is what worked for me: (test.jar is in same directory as the other files)
let java= require('java');
java.classpath.push('test.jar');
let mySumTest= java.import("MySumClass");
/*
//this prints out undefined, don't know why
console.log(java.callStaticMethod("MySumClass", "sum", 2, 5, function(err, results){
if(err){
console.error(err);
return;
}
else return results;
}));
*/
var result= java.callStaticMethodSync("MySumClass", "sum", 2, 5)
console.log(result)
It may be better to just create a java server to do the computations and communicate with your node.js application over a messaging queue. Here is an example which shows how to do that - http://blog.james-carr.org/2010/09/09/rabbitmq-nodejs-and-java-goodness/
You might want to take a look a Vert.X, which will let you mix and match JavaScript and Java as you see fit and communicate via a local message bus.