Example of DatatypeConverter in Java

By Arvind Rai, November 14, 2023
If we need to convert XML schema data types, we need to go through the knowledge of xml schema data type and lexical representation. DatatypeConverter class of the package javax.xml.bind can do all to convert xml schema data type to Java data type. DatatypeConverter has print and parse methods. print method encodes the data into lexical representation of xsd. And parse method can decode the lexical representation to string.

DatatypeConverterTest.java
package com.concretepage;
import java.util.Calendar;
import javax.xml.bind.DatatypeConverter;
public class DatatypeConverterTest {
  public static void main(String[] args) {
       //Testing DatatypeConverter.printBase64Binary
       String s1 = "Testing DatatypeConverter.printBase64Binary";
       String encodeds1 = DatatypeConverter.printBase64Binary(s1.getBytes());
       System.out.println(encodeds1);
       byte[] decodeds1= DatatypeConverter.parseBase64Binary(encodeds1);
       System.out.println(new String(decodeds1));
       
       //Testing  DatatypeConverter.printHexBinary
       String s2 = "Testing  DatatypeConverter.printHexBinary";
       String encodeds2 = DatatypeConverter.printHexBinary(s2.getBytes());
       System.out.println(encodeds2);
       byte[] decodeds2= DatatypeConverter.parseHexBinary(encodeds2);
       System.out.println(new String(decodeds2));
       
       //Lexical representation of date time
       System.out.println(DatatypeConverter.printDateTime(Calendar.getInstance()));
   }
}
Output
VGVzdGluZyBEYXRhdHlwZUNvbnZlcnRlci5wcmludEJhc2U2NEJpbmFyeQ==
Testing DatatypeConverter.printBase64Binary
54657374696E6720204461746174797065436F6E7665727465722E7072696E7448657842696E617279
Testing  DatatypeConverter.printHexBinary
2013-03-15T18:23:25.830+05:30 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us