James
----- Original Message -----
From: "Christian Holmqvist, IT, Posten" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
Sent: Tuesday, April 30, 2002 9:00 AM
Subject: [dom4j-user] Is this a bug? Or a double mystery.... that want's a
solution....
> Hi!
>
> I'm trying to add a element after another element if the element is
present
> (the element should be present, if present, as the first element). The
code
> I run is:
>
> XPath xp = DocumentHelper.createXPath("/*/header");
> Node n = xp.selectSingleNode(getDocMain());
> if(n != null)
> {
> int headerIndex = getDocMain().indexOf(n);
> doc.content().add(headerIndex + 1, elemToAdd);
> }
> else
> {
> doc.content().add(0, elemToAdd);
> }
>
> doc is ofcourse a Document and elemToAdd is a element (not yet connected
to
> a Document)...
>
> When running this (and n ends up not being null) the result of headerIndex
> is -1. This can't be right since I just picked up the node to find the
index
> for from the document???!!!
The <header> elements will be children of the documents root Element - not
children of the document.
The "/" XPath matches the document node
The "/*" XPath matches the root element.
The "/*/headers" XPath matches children of the root element.
So if you change this line
> int headerIndex = getDocMain().indexOf(n);
> doc.content().add(headerIndex + 1, elemToAdd);
to
List headers = doc.getRootElement().content();
int headerIndex = headers.indexOf(n);
headers.add(headerIndex + 1, elemToAdd);
You should be fine.
James
_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com
_______________________________________________
dom4j-user mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/dom4j-user