How to add xml nodes (as a string) to an existing XML node element (only using embedded java systems)?

(Disclaimer: Using Rhino Inside RingoJS)

Let's say I have a document with an element, I don’t see how I can add nodes as a string to this element. To parse the string into xml nodes and then add them to the node, I tried to use documentFragment, but I could not go anywhere. In short, I need something as simple as .NET.innerXML, but this is not in java-api.

var dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); var dBuilder = dbFactory.newDocumentBuilder(); var doc = dBuilder.newDocument(); var el = doc.createElement('test'); var nodesToAppend = '<foo bar="1">Hi <baz>there</baz></foo>'; el.appendChild(???); 

How can I do this without using any third-party library?

[EDIT] This is not obvious in the example, but I should not know the contents of the variable 'nodesToAppend'. Therefore, please do not point me to tutorials on how to create elements in an XML document.

+4
source share
2 answers

You can do this in java - you can get the Rhino equivalent:

 DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); Element el = doc.createElement('test'); doc.appendChild(el); String xml = "<foo bar=\"1\">Hi <baz>there</baz></foo>"; Document doc2 = builder.parse(new ByteArrayInputStream(xml.getBytes())); Node node = doc.importNode(doc2.getDocumentElement(), true); el.appendChild(node); 

Since doc and doc2 are two different Document , the trick is to import a node from one document to another, which is done using the importNode api above

+8
source

I think your question is similar to this question and it has the answer: Java: how to read and write xml files?

OR see the link http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

0
source

Source: https://habr.com/ru/post/1442598/


All Articles