2014-04-23 77 views
1

我有具有許多元素評論XML文件。從所有這些元素中,我想使用sed命令取消註釋一個元素。取消註釋XML塊

我有XML文件:

<!-- 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> 

在上面的XML文件,我想取消註釋最後一個XML塊,所以我的文件看起來像

<!-- 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> 

我通過sed命令不見了,但沒有得到如何從最後一個塊刪除<!----><name>NewName是否可以取消註釋xml塊?除了刪除整行之外,我沒有發現任何東西。

編輯:我可以有許多xml元素,而不是<name><id><address>, <city>, <class>,<marks>

+0

在你只輸入第一個'student'被評論所包圍。第三不是。實際上,輸入不是有效的XML。 –

+0

我已經更新了這個問題。錯誤地在這裏輸入了錯誤。但問題仍然存在 –

+0

我懷疑你想做什麼是可能的。解析XML很困難。 –

回答

1

這可能會爲你工作(GNU SED):

sed -r '/<Students>/,/<\/Students>/{/<Students>/{h;d};H;/<\/Students>/!d;g;s/(.*)<!-- (.*) -->(.*)/\1\2\3/}' file 

此存儲在保持空間個數據然後使用貪婪找到<!---->最後發生和打印數據之前刪除它們。

+0

這裏我想刪除最後一個只有作爲NewName的學生元素。學生是父母的標籤,學生是孩子的元素。所以我很困惑你的命令模式匹配 –

+0

@Optimus這存儲多行,然後刪除最後的開始/結束評論標籤。 – potong

+0

謝謝@potong,請您告訴我爲什麼\ 1 \ 2 \ 3是必需的? –

1

不要使用sed。使用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) = '&lt;']"> 
    <xsl:value-of select="." disable-output-escaping="yes" /> 
    </xsl:template> 
</xsl:stylesheet> 
在命令行上

 
xsltproc -o output.xml uncomment.xsl input.xml 

如果它工作正常,你得到這個你輸入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>