wood burning stoves 2.0*
The moose likes XML and Related Technologies and the fly likes Adding a comment to an XML tag Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Adding a comment to an XML tag" Watch "Adding a comment to an XML tag" New topic
Author

Adding a comment to an XML tag

igwe kalu kalu ogba
Ranch Hand

Joined: Feb 03, 2005
Posts: 133
Hello, I was wondering how to add a comment to an XML tag. The method I have uses insertBefore, which will add the comment like this:

<!--helloworld--><bomb></bomb.

But what I want is this:

<!--helloworld<bomb></bomb>-->

Thanks.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
What you describe removes the <bomb> element entirely from the document, substituting a comment that contains the bomb text. Is that what you really want?
Note that it is possible - when playing with Comment nodes - to create XML that is unparsable - for example by adding "--" in the text anywhere.
Bill
igwe kalu kalu ogba
Ranch Hand

Joined: Feb 03, 2005
Posts: 133
Well, what I want is a comment that encloses the bomb element. Such that if I have an element called <bomb></bomb>, it will be enclosed in a comment. Thanks.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
See the createComment(String ) method in org.w3c.dom.Document - it creates a Node of type COMMENT_NODE that you will have to insert in place of the <bomb> element. The remainder is left as a student exercise.
igwe kalu kalu ogba
Ranch Hand

Joined: Feb 03, 2005
Posts: 133
Thanks William, this is what i did:

Element root = doc.createElement("local-tx-datasource");

Comment domain = doc.createComment("<bomb></bomb>");

Then, later in my code:

root.appendChild(domain);
Where root is the top element.

Ok, so I have just one more question. I want to be able to change the node domain into an uncommented node at will. I know that Element has a method called removeChild. The problem is this, if I am parsing an XML file, I cann ot view comments. Is there a way of detecting comments and removing them, so that I can now create an Element

Element domain = doc.createElement("bomb");

and then use the root.appendChild(domain) method to add a new domain?

Thank you.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
Whether or not a parser ignores comments depends on settings you may be able to change depending on the parser toolkit.
See for example javax.xml.parsers.DocumentBuilderFactory
Bill
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Adding a comment to an XML tag