如何仅使用XSLT取消特定navref元素的注释
我来帮你搞定这个需求——你需要用XSLT精准地把XML中被注释的<navref>元素还原成正常节点,同时保留其他所有内容(包括其他注释、元素结构、属性等)完全不变对吧?
先分析你当前代码的问题
你现有的XSLT会把所有注释都通过disable-output-escaping="yes"直接输出,这会导致所有注释内容都变成普通文本/节点,不符合你只处理特定<navref>注释的要求。
正确的XSLT实现方案
我们需要保留默认的身份转换逻辑(确保大部分内容原样复制),同时只针对包含<navref>的注释做特殊处理:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0"> <!-- 身份转换模板:默认复制所有节点和属性,保持原样 --> <xsl:template match="node() | @*"> <xsl:copy> <xsl:apply-templates select="node() | @*"/> </xsl:copy> </xsl:template> <!-- 只处理包含navref的注释,优先级高于身份模板 --> <xsl:template match="comment()[contains(., '<navref')]" priority="2"> <!-- 解析注释中的XML片段并输出 --> <xsl:copy-of select="parse-xml-fragment(.)"/> </xsl:template> <!-- 其他注释原样保留 --> <xsl:template match="comment()" priority="1"> <xsl:copy/> </xsl:template> </xsl:stylesheet>
关键部分说明
- 身份转换模板:这是XSLT的基础模板,确保所有未被特殊模板匹配的内容(元素、属性、文本、其他注释)都原样复制到输出中。
- 特定注释处理模板:通过
comment()[contains(., '<navref')]精准匹配包含<navref>的注释,使用parse-xml-fragment()把注释里的XML字符串解析成真实的XML节点,然后输出这个节点,替代原来的注释。 - 优先级设置:给两个注释模板设置不同优先级,确保特定注释的模板先被匹配,其他注释则被原样保留。
测试用例验证
XML输入
<?xml version="1.0" encoding="UTF-8"?> <topicgroup collection-type="sequence"> <!--Handling topicref with navref--> <topicref collection-type="sequence" id="107746" href="../../../../../../Section_General_Notes/107746.dita"> <topicmeta> <navtitle/> <critdates> <created date="09-Apr-2009" golive="01-Jul-2009" expiry=""/> </critdates> <data name="section_num" value="55"/> </topicmeta> </topicref> <!--<navref mapref="../../../../../../Section_General_Notes/107746.ditamap"/>--> </topicgroup>
期望输出
<?xml version="1.0" encoding="UTF-8"?> <topicgroup collection-type="sequence"> <!--Handling topicref with navref--> <topicref collection-type="sequence" id="107746" href="../../../../../../Section_General_Notes/107746.dita"> <topicmeta> <navtitle/> <critdates> <created date="09-Apr-2009" golive="01-Jul-2009" expiry=""/> </critdates> <data name="section_num" value="55"/> </topicmeta> </topicref> <navref mapref="../../../../../../Section_General_Notes/107746.ditamap"/> </topicgroup>
这个方案完全符合你的需求:只取消目标<navref>的注释,其他内容(包括顶部的注释、topicref结构)都保持不变。
内容的提问来源于stack exchange,提问作者Umaima Fatima
相关产品推荐
相关产品推荐

