Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Thursday, May 9, 2013

Sorting xml based on a tag value

If we want to sort an xml based on a field's value, we can use the following approch

Say for e.g  This is the source xml



<?xml version="1.0" encoding="UTF-8"?>
<OrganizationList>
   <Organization>
      <Name>Bharath</Name>
      <System>automotive</System>
      <main>Y</main>
   </Organization>
   <Organization>
      <Name>ATP</Name>
      <System>supply</System>
      <main>N</main>
   </Organization>
   <Organization>
      <Name>BSNL</Name>
      <System>service</System>
      <main>Y</main>
   </Organization>
</OrganizationList>


If we want to sort the above xml based on the value of main tag we can use the following approach




<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" exclude-result-prefixes="xsl">
   <xsl:template match="node()">
      <xsl:copy>
         <xsl:apply-templates />
      </xsl:copy>
   </xsl:template>
   <xsl:template match="OrganizationList">
      <xsl:copy>
         <xsl:apply-templates>
            <xsl:sort order="descending" select="main" />
         </xsl:apply-templates>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>


The result will be as shown below



<?xml version="1.0" encoding="UTF-8"?>
<OrganizationList>
   <Organization>
      <Name>Bharath</Name>
      <System>automotive</System>
      <main>Y</main>
   </Organization>
   <Organization>
      <Name>BSNL</Name>
      <System>service</System>
      <main>Y</main>
   </Organization>
   <Organization>
      <Name>ATP</Name>
      <System>supply</System>
      <main>N</main>
   </Organization>
</OrganizationList>





Wednesday, November 7, 2012

Remove namespace from xml

Sometime we might need to remove all the namespaces from an xml document.

Here is piece of java code which does that job !!


public static String removeNamespaces(String s)
 {
     Transformer transformer = null;
     try
     {
         transformer = templates.newTransformer();
     }
     catch(TransformerConfigurationException transformerconfigurationexception)
     {
         System.err.println("Error transforming XML");
         transformerconfigurationexception.printStackTrace();
         return null;
     }
     StringReader stringreader = new StringReader(s);
     StringWriter stringwriter = new StringWriter();
     try
     {
         transformer.transform(new StreamSource(stringreader), new StreamResult(stringwriter));
         return stringwriter.toString();
     }
     catch(TransformerException transformerexception)
     {
         System.err.println("Error transforming XML");
         transformerexception.printStackTrace();
         return null;
     }
 }