请求编写XSLT:将含title/artist/country的XML转换为指定结构XML
解决XSLT转换XML字段拼接与替换的问题
输入XML示例
<root> <item> <title>Hello World</title> <artist>John Doe</artist> <country>USA</country> </item> <item> <title>My Song</title> <artist>Jane Smith</artist> <country>Canada</country> </item> </root>
期望输出XML示例
<root> <item> <title_and_artist>Hello World - John Doe</title_and_artist> <address>USA</address> </item> <item> <title_and_artist>My Song - Jane Smith</title_and_artist> <address>Canada</address> </item> </root>
正确的XSLT转换代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 匹配根节点,保留根结构并遍历所有item --> <xsl:template match="/root"> <root> <xsl:apply-templates select="item"/> </root> </xsl:template> <!-- 处理单个item节点 --> <xsl:template match="item"> <item> <!-- 拼接title和artist生成新字段 --> <title_and_artist> <xsl:value-of select="title"/> <xsl:text> - </xsl:text> <xsl:value-of select="artist"/> </title_and_artist> <!-- 将country内容转移到address字段 --> <address> <xsl:value-of select="country"/> </address> </item> </xsl:template> </xsl:stylesheet>
关键说明
- 核心逻辑是通过模板匹配分别处理根节点和每个
item节点,保留整体XML结构。 - 拼接字段时用
<xsl:value-of>提取原字段文本,<xsl:text>添加自定义分隔符(可根据需求修改为其他符号)。 - 如果需要处理空值场景(比如某条数据没有artist),可以加判断逻辑优化:
<title_and_artist> <xsl:value-of select="title"/> <xsl:if test="artist != ''"> <xsl:text> - </xsl:text> <xsl:value-of select="artist"/> </xsl:if> </title_and_artist>
内容的提问来源于stack exchange,提问作者Mohsin Arain
相关产品推荐
相关产品推荐

