Created
July 6, 2016 09:55
-
-
Save kapilraj2436/e90fdb0069493e9bf3482e6d34c828a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.JSONObject; | |
import org.json.XML; | |
import java.io.*; | |
public class ConvertXMLToJson{ | |
public static void main(String[] args) throws Exception | |
{ | |
String fileName = "D:\\temp.json"; | |
try | |
{ | |
File file = new File ("D:\\example.xml"); | |
InputStream inputStream = new FileInputStream(file); | |
StringBuilder builder = new StringBuilder(); | |
int ptr = 0; | |
while ((ptr = inputStream.read()) != -1 ) | |
{ | |
builder.append((char) ptr); | |
} | |
String xml = builder.toString(); | |
JSONObject jsonObj = XML.toJSONObject(xml); | |
System.out.println(jsonObj.toString()); | |
System.out.println(jsonObj.toString().split(",").length); | |
// Assume default encoding. | |
FileWriter fileWriter = new FileWriter(fileName); | |
// Always wrap FileWriter in BufferedWriter. | |
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); | |
// Always close files. | |
for(int i= 0 ;i < jsonObj.toString().split(",").length; i ++) { | |
System.out.println(jsonObj.toString().split(",")[i]); | |
bufferedWriter.write(jsonObj.toString().split(",")[i]); | |
bufferedWriter.write("\n"); | |
} | |
bufferedWriter.close(); | |
} | |
catch(IOException ex) | |
{ | |
System.out.println("Error writing to file '"+ fileName + "'"); | |
} | |
catch(Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0"?> | |
<company> | |
<Details> | |
<fname>kapilraj</fname> | |
<lastname>Chouhan</lastname> | |
<nickname>kappu</nickname> | |
<salary>1000</salary> | |
<address>Delhi NCR</address> | |
<pin>458990</pin> | |
</Details> | |
<Details> | |
<firstname>nitin</firstname> | |
<lastname>Chouhan</lastname> | |
<nickname>nit</nickname> | |
<salary>1000</salary> | |
<address>Delhi NCR</address> | |
<pin>458990</pin> | |
</Details> | |
</company> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment