Remove/add XML comment

Hi,

Anyone know if possible to remove comment from commented XML node?

For example, see this XML:

<Project>
<Site>My Site</Site>
<!--
<Test>
     <Node>Value</Node>
</Test>
-->
</Project>

I want to to remove the comment <!-- -->, so it will become:

<Project>
<Site>My Site</Site>
<Test>
     <Node>Value</Node>
</Test>
</Project>

But I also need to be able to comment it again:

<Project>
<Site>My Site</Site>
<!--
<Test>
     <Node>Value</Node>
</Test>
-->
</Project>


We can use "Test" as the node name for this problem.
Reason that my application need to be able to toggle this <Test> node based on certain situation.

I could think of DELETE and RE-ADD, but it will be quite complicated because I need to have that <Test> node in specific location within the XML file (Under the <Site> node).
Of course the actual XML has much more contects in between.

klompenAsked:
Who is Participating?
 
Emmanuel PASQUIERFreelance Project ManagerCommented:
you could remove completely the comment start and stop comment '<!--' and '-->', but to reverse you would need to find the <Test> and </Test> and put them back again . That can be complicated, and If you ever need to have anything else than one Test node within, you'll have problems.
What about closing the start comment directly and same for the end of the comment tag ?
You'll get something like :

<Project>
<Site>My Site</Site>
<!--START TEST COMMENT-->
<Test>
     <Node>Value</Node>
</Test>
<!--END TEST COMMENT-->
</Project>

so from a parser point of view that would be equivalent to what you need, and reversing that is simple, whatever was within the comment
Const
 StartComment='<!--START TEST COMMENT-->';
 EndComment='<!--END TEST COMMENT-->';

procedure IncludeCommentedTest(XML:String):String;
begin
 Result:=StringReplace(XML,'-->',EndComment,[rfReplaceAll]);
 Result:=StringReplace(Result,'<!--',StartComment,[rfReplaceAll]);
end;

procedure ExcludeCommentedTest(XML:String):String;
begin
 Result:=StringReplace(XML,EndComment,'-->',[rfReplaceAll]);
 Result:=StringReplace(Result,StartComment,'<!--',[rfReplaceAll]);
end;

Open in new window

0
 
Eddie ShipmanAll-around developerCommented:
How are you operating on this XML? TXMLDocument or IXMLDOMDocument?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.