如何使用XSLT在XML中新增DeptName元素并提取Dept字段后半段值
XSLT实现XML新增DeptName元素转换方案
实现思路
- 采用XSLT身份复制模板原样保留所有原有节点、属性及内容,无需手动逐个定义要复制的节点
- 匹配顶层
<Name>元素,在复制原有子节点的基础上,新增<DeptName>元素,通过字符串处理提取Dept字段中-分隔的第二部分作为值
完整XSLT代码(兼容XSLT 1.0,适用性最广)
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 身份复制模板:原样复制所有节点和属性 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配Name根节点,新增DeptName元素 --> <xsl:template match="Name"> <xsl:copy> <!-- 复制原有所有子节点 --> <xsl:apply-templates select="@*|node()"/> <!-- 新增DeptName,取Dept字段中-后面的内容 --> <DeptName> <xsl:value-of select="substring-after(Dept, '-')"/> </DeptName> </xsl:copy> </xsl:template> </xsl:stylesheet>
XSLT 2.0及以上版本可选写法(支持多分隔符场景)
如果Dept字段存在多个-,需要准确取第二个分段,可以用2.0新增的tokenize函数实现:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="Name"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <DeptName> <!-- tokenize按-拆分后取第二个元素,索引从1开始 --> <xsl:value-of select="tokenize(Dept, '-')[2]"/> </DeptName> </xsl:copy> </xsl:template> </xsl:stylesheet>
效果说明
以上代码转换后会完全保留原有XML的所有内容,仅在<Dept>元素同级位置新增<DeptName>元素,输出结果完全符合预期要求。
内容的提问来源于stack exchange,提问作者Raghu
相关产品推荐
相关产品推荐

