| Author |
Removing the XML node from a DOM object
|
Paul Policarp
Greenhorn
Joined: May 07, 2010
Posts: 18
|
|
Hi.
I'm using the w3 DOM API for XML manipulation and need to add a subtree (constructed by using "parse()" on a ByteArrayInputStream derived from a string) to another DOM.
I get a org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
I think this is because the DOM created with parse() also contains the <?xml version...etc> tag. How can I remove it?
Here's the code sample:
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Node, which is extended by both Document and Element, has methods getParentNode() and removeChild(Node). So you can detach any Node from its parent as such:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Paul Policarp
Greenhorn
Joined: May 07, 2010
Posts: 18
|
|
Ok, but my XML looks like this:
<?xml version=1.0...>
<snapshot>
<node> value<node>
.
.
.
</snapshot>
I need everything BUT "<?xml version=1.0...>" as a DOM. Can I remove it with removeChild? Does it have a parent node?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
What happens if you print out parent?
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
Paul Policarp wrote:I get a org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
I think this is because the DOM created with parse() also contains the <?xml version...etc> tag. How can I remove it?
No, that's a completely wrong guess at the problem. The problem is exactly what the error message says it. To fix the problem, have a look at the Document.importNode method.
|
 |
Paul Policarp
Greenhorn
Joined: May 07, 2010
Posts: 18
|
|
This is how I amended the code:
And then inserted your code. This is my output:
*****#document
++++++snapshot
And then I get a NullPointerException on
configNode.appendChild(inlineDoc.getDocumentElement());
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
Paul Policarp wrote:Ok, but my XML looks like this:
<?xml version=1.0...>
<snapshot>
<node> value<node>
.
.
.
</snapshot>
I need everything BUT "<?xml version=1.0...>" as a DOM. Can I remove it with removeChild? Does it have a parent node?
No, that's a completely wrong understanding of DOM. Your DOM only contains the nodes of the document. It doesn't "contain" the prolog from the text version of the document; the prolog is produced when you serialize the DOM.
If you don't want your serialized document to contain a prolog, then do something differently in the serialization process to exclude the prolog.
|
 |
Paul Policarp
Greenhorn
Joined: May 07, 2010
Posts: 18
|
|
|
Thanks, I didn't know all these things. Import node worked like a charm once I got the hang of it.
|
 |
 |
|
|
subject: Removing the XML node from a DOM object
|
|
|