0

I need to make XML out of response in XML format. For some fields, I need to be able to change the value. I also need to remove all fields that are not mapped.

I get responses that look like this

<response>
  <DOCUMENTS>
     <DOCUMENT>
        <KODA>AA</KODA>
        <ITEMS>
          <ITEM>B</ITEM>
          <ITEM>C</ITEM>
       </ITEMS>
     </DOCUMENT> 
  </DOCUMENTS>
</response>

and want to make of it something that looks like below

<EXPORT>
  <DOCUMENTS>
     <DOCUMENT>
        <KODDZ>SS</KODDZ>
        <VALUES>
          <VALUE>B</VALUE>
          <VALUE>C</VALUE>
       </VALUES>
     </DOCUMENT>
 </DOCUMENTS> 
</EXPORT>

I have been trying using the XSLT example from this question but without success. Basically what would be best for me would be a solution that takes some kind of map of fields for example:

map_of_values = {"response/DOCUMENTS/DOCUMENT/KODA":"EXPORT/DOCUMENTS/DOCUMENT/KODZA",
"response/DOCUMENTS/DOCUMENT/ITEMS/ITEM":EXPORT/DOCUMENTS/DOCUMENT/VALUES/VALUE}

What would be the best way to achieve a static map kind of solution?

Adrian
  • 149
  • 3
  • 16
  • 1
    That is not even the right XML syntax with all that markup like `B`. Otherwise it looks like a task for XML although obviously you want to map `response` to `EXPORT` and map the `KODZA`, the `ITEMS` and the `ITEM` elements as well so you need four templates plus the identity transformation. – Martin Honnen Mar 27 '22 at 13:38
  • I have edited the example to proper XML(thanks for the notice). I will read more on templates and identity transformation, thank you. – Adrian Mar 27 '22 at 15:55

1 Answers1

1

In terms of XSLT you seem to want something along the lines of

 <xsl:template match="response">
    <EXPORT>
      <xsl:apply-templates/>
    </EXPORT>
  </xsl:template>
  
  <xsl:template match="KODA">
    <KODDZ>
      <xsl:apply-templates/>
    </KODDZ>
  </xsl:template>
  
  <xsl:template match="KODA/text()[. = 'AA']">
    <xsl:text>SS</xsl:text>
  </xsl:template>

  <xsl:template match="ITEMS">
    <VALUES>
      <xsl:apply-templates/>
    </VALUES>
  </xsl:template>
  
  <xsl:template match="ITEM">
    <VALUE>
      <xsl:apply-templates/>
    </VALUE>
  </xsl:template>

plus the identity transformation template, of course.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110