Shariq
Shariq

Reputation: 2824

XML parsing in JAVA, transformation from one Schema to other

How to parse XML in java. I have one XML given below :

<?xml version="1.0" ?>
<metabase>
  <response status="SUCCESS"/>
  <item>
    <id>10147417040</id>
    <description>
      <title>What part of the constitiution states the goals?</title>
      <language>English</language>
   </description>
   <pubDate>2012-03-27 07:25:33.0</pubDate>
  </item>
  <item>
    <id>10147417018</id>
    <description>
      <title>What is the work envelope of a robot car?</title>
      <language>English</language>
    </description>
    <pubDate>2012-03-27 07:25:33.0</pubDate>
  </item>
</metabase>

I want to parse this XML and convert into the form:

<?xml version="1.0" ?>
<add>
  <doc>
    <field name="id">10147417040</field>
    <field name="title">What part of the constitiution states the goals?</field>
    <field name="language">English</field>
    <field name="pubDate">2012-03-27 07:25:33.0</field>
  </doc>
  <doc>
    <field name="id">10147417018</field>
    <field name="title">What is the work envelope of a robot car?</field>
    <field name="language">English</field>
    <field name="pubDate">2012-03-27 07:25:33.0</field>
  </doc>
</add>

Please give some Sample JAVA code to do this task.

Thanks Shariq

Upvotes: 0

Views: 1306

Answers (1)

MiMo
MiMo

Reputation: 11953

The best way to do this kind of XML-to-XML transformations is to use an XSLT. Here is the XSLT that does what you need:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

  <xsl:template match="item">
    <doc>
      <field name="id">
        <xsl:value-of select="id" />
      </field>
      <field name="title">
        <xsl:value-of select="description/title" />
      </field>
      <field name="language">
        <xsl:value-of select="description/language" />
      </field>
      <field name="pubDate">
        <xsl:value-of select="pubDate" />
      </field>
    </doc>
  </xsl:template>

  <xsl:template match="/">
    <add>
      <xsl:apply-templates/>
    </add>
  </xsl:template>

</xsl:stylesheet>

I am not familiar with Java but I am sure that here is an easy way to load an XSLT and apply it to an XML - see for example http://www.devx.com/getHelpOn/10MinuteSolution/16635/1954

Upvotes: 1

Related Questions