简体   繁体   中英

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

I have a CSV file in which key value pairs is present

Key1,Value1
Key2,Value2
Key3,Value3

My XML data looks like this

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

I want to build XSL file to transform xml data into tabular format with two columns like this.

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

I have the code ready to transform data and display into tabular format. But I am unable to find the code to build key value pair map and substitute xml key with the value present in csv file. I went through lot of stack overflow questions but couldn't find much help. Please walk me through the process to read csv file and build a map and later substitute key for its value. Thanks

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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