6

(Disclaimer: using Rhino inside RingoJS)

Let's say I have a document with an element , I don't see how I can append nodes as string to this element. In order to parse the string to xml nodes and then append them to the node, I tried to use documentFragment but I couldn't get anywhere. In short, I need something as easy as .NET's .innerXML but it's not in the 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] It's not obvious in the example but I'm not supposed to know the content of variable 'nodesToAppend'. So please, don't point me to tutorials about how to create elements in an xml document.

user1780705
  • 63
  • 1
  • 1
  • 4

2 Answers2

14

You can do this in java - you should be able to derive 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 Documents the trick is to import the node from one document to another, which is done with the importNode api above

Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • Excellent answer, thanks very much ! I was missing the importNode when trying to bring a node from another document. Sorry I could not up the answer but I have not enough reputation :-) – user1780705 Oct 28 '12 at 17:16
0

I think your question is like this question and there is answer on it : Java: How to read and write xml files?

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

Community
  • 1
  • 1
Mohamed Habib
  • 883
  • 1
  • 8
  • 18
  • No. I figured out how to parse an XML file with java but in my case I'm stuck with appending a set of element from a string. I tried to create another document using StringReader and InputSource in order to use the string as source. But I can't move the element from a document to another. – user1780705 Oct 28 '12 at 15:47