使用XSL将<w:t>节点值复制到<w:c>节点及避免命名空间冗余
问题解决:将<w:t>的值复制到<w:c>并消除冗余命名空间
问题描述
需要将XML中<w:t>节点的内容(示例中的"2")复制到<w:c>节点中,同时避免<w:c>自动添加冗余的xmlns:w命名空间属性。此前尝试使用key和直接xsl:value-of的方式均未得到预期结果。
错误分析
第一个XSL尝试的问题:
- 错误定义
key:匹配w:document节点并使用w:t作为索引,不符合需求; - 仅重写
w:c模板,未处理其他节点,导致默认模板输出<w:t>的文本内容,且xsl:copy-of选择的是整个w:document节点,无法正确填充值; - 未保留原XML的结构和命名空间声明,导致
<w:c>被迫重新添加命名空间。
- 错误定义
第二个XSL尝试的问题:
- 直接在
xsl:stylesheet下编写<w:document>节点,不符合XSLT的模板驱动逻辑; - 路径选择错误,上下文节点为根节点时,
w:document/w:t无法正确定位目标节点。
- 直接在
正确解决方案
使用身份转换模板保留原XML的所有结构、属性和命名空间,仅针对<w:c>节点重写模板,填充目标值。
修正后的format3.xsl代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <!-- 身份转换模板:复制所有原节点和属性,保留结构与命名空间 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 重写w:c节点的处理逻辑 --> <xsl:template match="w:c"> <xsl:copy> <!-- 定位根节点下的w:document中的w:t节点,获取其文本值 --> <xsl:value-of select="/w:document/w:t"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
代码说明
- 身份转换模板确保原XML的所有节点(包括
<w:document>的命名空间声明、<w:t>节点)都被完整复制; - 针对
<w:c>的模板,使用xsl:copy复制节点本身(继承父节点的w命名空间,避免冗余声明),然后通过绝对路径/w:document/w:t获取目标值并填充。
执行结果
运行原index.php代码后,生成的newfile.xml将与预期输出完全一致:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"> <w:t>2</w:t> <w:c>2</w:c> </w:document>
内容的提问来源于stack exchange,提问作者Premlatha
相关产品推荐
相关产品推荐

