aspose file tools*
The moose likes XML and Related Technologies and the fly likes comment a node/element in xml file using java dom parser Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "comment a node/element in xml file using java dom parser" Watch "comment a node/element in xml file using java dom parser" New topic
Author

comment a node/element in xml file using java dom parser

Vijay Bhuruk
Ranch Hand

Joined: Feb 28, 2008
Posts: 31

I need way to comment out particular node/element in xml file.

what I am doing is
1.parse xml file using dom parser.
2.traverse through child nodes. check node values if it matches to given input value.
3. comment out entire node whose node value==given input.

I can create new comment node and insert or append in document or child. but want to comment already existing node.



here, I want to comment node <title>

William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12805
    
    5
You can't change the Node type in place.

I believe you will have to remove the Node entirely from the Document, then createComment( text ) with the text and finally add it back to the document.

Or possibly you could use the replaceChild( newnode, oldnode ) method.

Bill
Vijay Bhuruk
Ranch Hand

Joined: Feb 28, 2008
Posts: 31

Bill, Thanks for reply.

Creating comment node with text seems a only workaround for now.

Node method- getTextContent() returns "Required Information". so newly created comment node will be like
<!-- Required Information -->

is there any way to get text string with node name. like "<tile>Required Information</title>". so that comment will be like
<!-- <title>Required Information </title> -->
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12805
    
    5
You would have to do that formatting in your own code.

Note that you can get the name of the node you are replacing with getNodeName() but you will still have to add the formatting "<" etc.

You should get familiar with the excellent table in the JavaDocs for org.w3c.dom.Node - which will help you understand the behavior of the various types of Node implementatiosn.

Bill
g tsuji
Ranch Hand

Joined: Jan 18, 2011
Posts: 535
    
    3
You should be able to do it by writing a specific xslt document to attain the objective. That would provide a solution with better isolation of concerns as you might have loaded the original xml to dom for the purpose of doing something useful other than commenting the title element...
Vijay Bhuruk
Ranch Hand

Joined: Feb 28, 2008
Posts: 31

Thanks g tsuji.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: comment a node/element in xml file using java dom parser