使用XSLT基于多字段匹配从合并XML文件中选取目标节点
实现方案
核心逻辑
- 遍历
fileA区段下的所有data节点 - 对每个节点以
id、color、quantaties三个字段为匹配条件,到fileB区段查找完全匹配的节点 - 匹配成功则输出
fileB对应的节点,否则输出当前fileA的节点
XSLT 1.0 实现(兼容性最佳)
以下代码可直接用于转换你的XML文件,适配绝大多数XSLT处理器:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <xsl:template match="/root"> <root> <newFile> <xsl:for-each select="fileA/data"> <xsl:variable name="currentId" select="id"/> <xsl:variable name="currentColor" select="color"/> <xsl:variable name="currentQty" select="quantaties"/> <xsl:variable name="matchNode" select="/root/fileB/data[id = $currentId and color = $currentColor and quantaties = $currentQty]"/> <xsl:choose> <xsl:when test="$matchNode"> <xsl:copy-of select="$matchNode"/> </xsl:when> <xsl:otherwise> <xsl:copy-of select="."/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </newFile> </root> </xsl:template> </xsl:stylesheet>
XSLT 2.0 优化实现(适合大数据量场景)
通过联合键索引提高匹配效率,数据量较大时性能明显优于1.0版本:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <!-- 定义三字段联合匹配键 --> <xsl:key name="dataMatchKey" match="fileB/data" use="concat(id, '|', color, '|', quantaties)"/> <xsl:template match="/root"> <root> <newFile> <xsl:for-each select="fileA/data"> <xsl:variable name="currentKey" select="concat(id, '|', color, '|', quantaties)"/> <xsl:choose> <xsl:when test="key('dataMatchKey', $currentKey)"> <xsl:copy-of select="key('dataMatchKey', $currentKey)"/> </xsl:when> <xsl:otherwise> <xsl:copy-of select="."/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </newFile> </root> </xsl:template> </xsl:stylesheet>
注意:如果实际业务中三个匹配字段的内容可能包含
|字符,请将拼接键的分隔符替换为字段值中不会出现的特殊字符,避免匹配错误。
内容的提问来源于stack exchange,提问作者egx
相关产品推荐
相关产品推荐

