简体   繁体   中英

Need to convert XML file to CSV file using XQUERY

I have a xml file.PFB the content:

<?xml version="1.0"?><Price-Data-Description xmlns:xsi="http://www.ybd3.org/2021/XMLSchema-instance">

<item id="Data_200_PRICE">
<Code>111</Code>
<Cur>12</Cur>
<Conv>600</Conv>
<Data>Float</Data>
<Year>1202</Year>
<Key>Data100-1202</Key>
</item>
<item id="Data_100_PRICE">
<Code>100</Code>
<Cur>199</Cur>
<Conv>900</Conv>
<Data>Integer</Data>
<Year>1302</Year>
<Key>Data200-1202</Key>
</item>
</Price-Data-Description>

I need it to get converted into csv file. PFB the content:

Code,Cur,Conv,Data,Year
111,12,600,Float,1202
100,199,900,Integer,1302

I have written an XQYERY, but the result is running empty. The XQYERY is validating and showing no error. PFB the XQUERY:

<SerializeToDelimitedContentTask>
   <filePath></filePath>
   <fileName>MyFile.csv</fileName>
    <skipHeaders>false</skipHeaders>
    { for $i in $input.fileEvent[1]/content//*:item
return
    <customObjects>
    <Code>{$i/Code/text()}</Code>
    <Cur>{$i/Cur/text()}</Cur>
    <Conv>{$i/Conv/text()}</Conv>
    <Data>{$i/Data/text()}</Data>
    <Year>{$i/Year/text()}</Year> 
    </customObjects>}
   <header>
      <fieldIndex>1</fieldIndex>
      <name>Code</name>
   </header>
   <header>
      <fieldIndex>2</fieldIndex>
      <name>Cur</name>
   </header>
   <header>
      <fieldIndex>3</fieldIndex>
      <name>Conv</name>
   </header>
   <header>
      <fieldIndex>4</fieldIndex>
      <name>Data</name>
   </header>
   <header>
      <fieldIndex>5</fieldIndex>
      <name>Year</name>
   </header>
</SerializeToDelimitedContentTask>

Its getting validated well with no errors and its generating a csv file 0 kb.

I am unsure of the Informatica implementation above, However, the simple example below is a generic translation script that works with your XML. Perhaps it can be used to help validate your approach.

It works from an XML fragment. If you are dealing with a document, then the xpath might be /Price-Data-Description/item rather than /item

(: farm the column names from the first record
   - assumes that the first record has all possible elements
:)
let $cols := for $node in $xml/item[1]/node()
  return fn:local-name($node)

(: make individual CSV style lines.
   Simple code does not take into account quoting or escaping
:)
let $rows := for $row in $xml/item
  return fn:string-join(
      for $col in $cols
        return fn:data($row/node()[fn:local-name(.) = $col])
    , ",")

(:make a header line:)
let $header := fn:string-join($cols, ",")

(:join them together with line-breaks:)
return fn:string-join(($header, $rows), "&#10;")

Result:

Code,Cur,Conv,Data,Year,Key
111,12,600,Float,1202,Data100-1202
100,199,900,Integer,1302,Data200-1202

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