繁体   English   中英

如何使用 csv 文件在 XSL 中构建键值对 map?

[英]How to build Key Value pair map in XSL using csv file?

我有一个 CSV 文件,其中存在键值对

Key1,Value1
Key2,Value2
Key3,Value3

我的 XML 数据看起来像这样

<root>
    <child1 attr1="Key1">some value 1</child1>
    <child2 attr1="Key2">some value 2</child2>
    <child3 attr1="Key3">some value 3</child3>
</root>

我想构建 XSL 文件以将 xml 数据转换为具有两列这样的表格格式。

|Value1|some value 1|
|Value2|some value 2|
|Value3|some value 3|

我已经准备好将数据转换为表格格式并显示的代码。 但我无法找到构建键值对 map 并用 csv 文件中存在的值替换 xml 键的代码。 我经历了很多堆栈溢出问题,但找不到太多帮助。 请引导我完成读取 csv 文件并构建 map 和稍后替换其值的密钥的过程。 谢谢

XSLT 3 and XPath 3.1 have a map datatype so there (eg Saxon 9.8 or later, Saxon JS 2, Altova XML 2017 R3 and later) you could use

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:map="http://www.w3.org/2005/xpath-functions/map"
  exclude-result-prefixes="#all"
  expand-text="yes">
  
  <xsl:param name="csv-file" as="xs:string" expand-text="no">data.csv</xsl:param>

  <xsl:param name="map" as="map(xs:string, xs:string)" 
    select="(unparsed-text-lines($csv-file) ! (let $tokens := tokenize(., ',') return map { $tokens[1] : $tokens[2] })) => map:merge()"/>

  <xsl:output method="text"/>
  
  <xsl:template match="/">
    <xsl:value-of select="root/* ! ('|' || $map(@attr1) || '|' || . || '|')" separator="&#10;"/>
  </xsl:template>
  
</xsl:stylesheet>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM