Reputation: 2385
I have xml file which has many elements commented. From all of these elements, I want to uncomment one element using sed command.
I have xml file as:
<!-- This is the sample xml
which holds the data of the students -->
<Students>
<!-- <student>
<name>john</>
<id>123</id>
</student> -->
<student>
<name>mike</name>
<id>234</id>
</student>
<!-- <student>
<name>NewName</name>
<id>NewID</id>
</student> -->
</Students>
In the above xml file, I want uncomment the last xml block, so my file will look like
<!-- This is the sample xml
which holds the data of the students -->
<Students>
<!-- <student>
<name>john</>
<id>123</id>
</student> -->
<student>
<name>mike</name>
<id>234</id>
</student>
<student>
<name>NewName</name>
<id>NewID</id>
</student>
</Students>
I gone through the sed command, but didn't get how can delete just <!--
and -->
from last block. Is it possible to uncomment xml block with <name>
as NewName
? I didn't find any thing apart from deleting whole line.
EDIT: I can have many xml elements other than <name>
and <id>
like <address>, <city>, <class>,<marks>
.
Upvotes: 2
Views: 1709
Reputation: 58473
This might work for you (GNU sed):
sed -r '/<Students>/,/<\/Students>/{/<Students>/{h;d};H;/<\/Students>/!d;g;s/(.*)<!-- (.*) -->(.*)/\1\2\3/}' file
This stores the Students
data in the hold space then uses greed to find the last occurence of <!--
and -->
and removes them before printing the data.
Upvotes: 1
Reputation: 338288
Don't use sed
. Use xsltproc
.
<!-- uncomment.xsl -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- this copies every input node unchanged -->
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<!-- this uncomments every comment that starts with a `<` -->
<xsl:template match="comment()[substring(normalize-space(), 1, 1) = '<']">
<xsl:value-of select="." disable-output-escaping="yes" />
</xsl:template>
</xsl:stylesheet>
on the command line:
xsltproc -o output.xml uncomment.xsl input.xml
If it works correctly, you get this for your input XML:
<!-- This is the sample xml
which holds the data of the students -->
<Students>
<student>
<name>john</name>
<id>123</id>
</student>
<student>
<name>mike</name>
<id>234</id>
</student>
<student>
<name>NewName</name>
<id>NewID</id>
</student>
</Students>
Upvotes: 2