Title: Message
Hey Doug
 
The first thing is to find the Element which is going to be the parent to which you are going to add a new element. The selectSingleNode() returns a Node because you could be finding the document ("/") or an attribute ("/foo/@x"), a namespace node ("namespace::*") or text node (":/foo/bar/text()"etc
 
So you just need to cast it if you know, from the XPath expression, that its going to be an Element.
 
e.g.
 
Element parent = (Element) doc.selectSingleNode(
    "//server_request/server/weblogic/internal"
);
// add a new element
parent.addElement( "server_address" ).addText( "192.10.20.41" );
 
The last add line could be more verbose if you wish. e.g.
 
Element serverAddress = parent.addElement( "server_address" );
serverAddress.addText( "192.10.20.41" );

James
----- Original Message -----
Sent: Monday, October 15, 2001 10:33 PM
Subject: [dom4j-user] Adding a node to the middle of a pre-existing DOM

Hi all,
 
    Just started playing with Dom4J and pretty impressed with it, so far. Question: I have a extremely large Xml object where I want to add an element to the middle of the Dom tree.  What's the most efficient way of doing this? 
 
For example, I want to create an element called <server_address>192.10.20.41</server_address> (where 192.10.20.41 is the text node) to <server_request><server><weblogic><internal>....
I was trying to use the selectSingleNode("//server_request/server/weblogic/internal") to get a Node() and use the addElement(), but the Node class doesn't have the addElement() method.
 
Could someone post the code for creating an element in the middle of a Xml Dom if I know what the XPath is to the parent element?
 
Any help is appreciated.
 
Doug Hoppes

Reply via email to