如何使用xmlstarlet或任何其他shell脚本库/工具等以编程方式在xml文件中注释/取消注释标记块。
...评论
输入文件:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
输出文件:
<note>
<to>Tove</to>
<!-- <from>Jani</from> -->
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
...取消注释
输入文件:
<note>
<to>Tove</to>
<!-- <from>Jani</from> -->
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
输出文件:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
答案 0 :(得分:1)
可以使用xsltproc
完成xsltproc comment-from.xslt input.xml
评论-from.xslt
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--Identity template,
provides default behavior that copies all content into the output -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!--More specific template for "from" that provides custom behavior -->
<xsl:template match="from">
<xsl:comment>
<xsl:text><![CDATA[ <from>]]></xsl:text>
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
<xsl:text><![CDATA[</from> ]]></xsl:text>
</xsl:comment>
</xsl:template>
</xsl:stylesheet>
答案 1 :(得分:1)
在玩xlstproc之后,我想出了一个解除注释案例的解决方案。 'contains'功能可以解决问题......
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!--Identity template,
provides default behavior that copies all content into the output -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!--More specific template for "from" that provides custom behavior -->
<xsl:template match="comment()">
<xsl:if test='contains(.,"<from>")' >
<xsl:value-of select="." disable-output-escaping="yes" />
</xsl:if>
<xsl:if test='not (contains(.,"<from>"))' >
<xsl:copy-of select="." />
</xsl:if>
</xsl:template>
</xsl:stylesheet>