0

I have a complex XML structure which I receive from 3rd party.I want to parse above XML document & create a Map with the respective values. Which library can be used to parse complex XML's

I tried XPath, however, I was unable to get desired result.

<OBJECT TYPE="BookListInterface" REF="OBJECT.BookListInterface">
    <Books TYPE="BookArray" length="5">
        <Item0 TYPE="BookName" REF="Item0.BookName.1">AA</Item0>
        <Item1 TYPE="BookName" REF="Item1.BookName.1">BB</Item1>
        <Item2 TYPE="BookName" REF="Item2.BookName.1">CC</Item2>
        <Item3 TYPE="BookName" REF="Item3.BookName.1">DD</Item3>
        <Item4 TYPE="BookName" REF="Item4.BookName.1">EE</Item4>
        <Item5 TYPE="BookName" REF="Item5.BookName.1">FF</Item5>
    </Books>
    <BookRates TYPE="DoubleArray" length="5">
        <Item0 TYPE="Double">10</Item0>
        <Item1 TYPE="Double">20</Item1>
        <Item2 TYPE="Double">30</Item2>
        <Item3 TYPE="Double">40</Item3>
        <Item4 TYPE="Double">50</Item4>
        <Item5 TYPE="Double">60</Item5>
    </BookRates>
</OBJECT>

I want to parse above XML document and create a Map with the respective values, i.e.

AA --> 10, 
BB --> 20 

and so on. How do I achieve this in JAVA?

zx485
  • 28,498
  • 28
  • 50
  • 59
Niche
  • 142
  • 1
  • 2
  • 9

1 Answers1

1

Apply this XSLT-1.0 template and you can get the wanted output:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:key name="keys" match="/OBJECT/Books/*" use="substring-after(local-name(),'Item')" />

    <xsl:template match="text()" />

    <xsl:template match="/OBJECT/BookRates/*">
      <xsl:variable name="number" select="substring-after(local-name(),'Item')" />
      <!-- Group this output to get a map result -->
        <xsl:value-of select="key('keys', $number)/text()" />  <!-- Mapping key -->
        <xsl:value-of select="' --> '" />
        <xsl:value-of select="text()" />                       <!-- Mapping value -->
        <xsl:value-of select="'&#xa;'" />
      <!-- End of grouping -->
    </xsl:template>

</xsl:stylesheet>

Its main function is mapping the values from /OBJECT/Books to the values of /OBJECT/BookRates/. This is achieved by creating a key value with substring-after(local-name(),'Item').

Its (text) output is:

AA --> 10
BB --> 20
CC --> 30
DD --> 40
EE --> 50
FF --> 60

In Java you can extract the marked Mapping key and Mapping value values from the result.

zx485
  • 28,498
  • 28
  • 50
  • 59