簡體   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