求助:为汇率数据编写适配的XSL样式表方案
适配欧洲央行带属性XML汇率数据的XSL样式表
假设你的欧洲央行XML数据为带命名空间、以属性存储核心信息的典型结构(示例如下),以下是修改后的XSL样式表,可将其转换为适合导入数据库的格式:
<!-- 欧洲央行XML示例结构 --> <gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> <gesmes:subject>Reference rates</gesmes:subject> <gesmes:Sender> <gesmes:name>European Central Bank</gesmes:name> </gesmes:Sender> <Cube> <Cube time="2024-05-20"> <Cube currency="USD" rate="1.0803"/> <Cube currency="GBP" rate="0.8572"/> <Cube currency="JPY" rate="165.23"/> </Cube> </Cube> </gesmes:Envelope>
适配的XSL样式表(转换为CSV)
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ecb="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> <xsl:output method="text" encoding="UTF-8"/> <!-- 输出CSV表头 --> <xsl:template match="/"> <xsl:text>date,currency,exchange_rate </xsl:text> <xsl:apply-templates select="//ecb:Cube[@time]/ecb:Cube[@currency and @rate]"/> </xsl:template> <!-- 提取每日汇率数据 --> <xsl:template match="ecb:Cube[@currency and @rate]"> <xsl:value-of select="../@time"/> <xsl:text>,</xsl:text> <xsl:value-of select="@currency"/> <xsl:text>,</xsl:text> <xsl:value-of select="@rate"/> <xsl:text> </xsl:text> </xsl:template> <!-- 忽略无关文本节点 --> <xsl:template match="text()"/> </xsl:stylesheet>
核心修改点
- 引入欧洲央行XML的命名空间,确保能精准匹配目标节点(原始XML带命名空间,必须显式声明才能正确解析)
- 使用
@属性名语法提取属性值,替代原样式表中提取元素内容的逻辑,比如@time取日期、@currency取货币代码、@rate取汇率 - 通过
//ecb:Cube[@time]/ecb:Cube[@currency and @rate]定位到有效汇率数据节点,过滤无效或无关内容
扩展:生成SQL插入语句
如果需要直接生成可执行的SQL插入语句,可修改XSL模板:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ecb="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="/"> <xsl:text>INSERT INTO exchange_rates (date, currency, exchange_rate) VALUES </xsl:text> <xsl:apply-templates select="//ecb:Cube[@time]/ecb:Cube[@currency and @rate]"/> </xsl:template> <xsl:template match="ecb:Cube[@currency and @rate]"> <xsl:text>('</xsl:text> <xsl:value-of select="../@time"/> <xsl:text>', '</xsl:text> <xsl:value-of select="@currency"/> <xsl:text>', '</xsl:text> <xsl:value-of select="@rate"/> <xsl:text>')</xsl:text> <xsl:if test="position() != last()">,</xsl:if> <xsl:text> </xsl:text> </xsl:template> <xsl:template match="text()"/> </xsl:stylesheet>
转换后的结果可直接导入数据库执行插入操作。
内容的提问来源于stack exchange,提问作者Andrej Macho
相关产品推荐
相关产品推荐

