Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding a comment to an XML tag  RSS feed

 
igwe kalu kalu ogba
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!