Java XPath

Quick way to extract data from XML is XPath.

http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

http://www.whitebeam.org/library/guide/TechNotes/xpath.rhtm

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import java.io.*;

String xmlData = "place the XML Data here.";
XPath xpath = XPathFactory.newInstance().newXPath();
InputStream inStream = new ByteArrayInputStream(xmlData.getBytes());
InputSource inputSource = new InputSource(inStream);
String nodeValue = xpath.evaluate("//nodeName", inputSource);
System.out.println("nodeValue==>" + nodeValue);

JAXB XJC [ERROR] Content is not allowed in prolog

D:project>xjc.exe -p com.package sample_schema.xsd
parsing a schema…
[ERROR] Content is not allowed in prolog.
line 1 of file:/D:/project/sample_schema.xsd

Remove this lines in xsd:

<?xml version="1.0" encoding="utf-16"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

add this lines in xsd:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

XML to Flat File or Database

Problem Statement: There is XML with 10k+ records. Need to convert into insert sql scripts.

Solution 1: XML –> XSD –> Java files –> Unmarshal XML

Step 1: Use XML Spy or Online tool to generate XSD for given XML.
http://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema.aspx

Step 2: Generate Java code for xsd

Option 1: Use Eclipse plugin. This is plugin is very old.
Use JAXB plugin to generate java code for given XSD.
https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html
This is very old plug in and not working with latest stuff…Even it works with older version, I dont want to use it.

Option 2: This is also not good idea. Because it works only with 1.5

Step 1: Download JAXB. It is part of JWSD. http://java.sun.com/webservices/downloads/previous/webservicespack.jsp

Step 2: Go to jaxbbin location and try following commands
>set JAVA_HOME=D:softwarejava_150_14
>set path=%JAVA_HOME%bin
>xjc.bat -p com.package example_schema.xsd

Option 3: xjc.exe is part of Java 1.6 and available in /bin folder.
>set JAVA_HOME=D:softwarejdk1.6.0_14
>set path=%JAVA_HOME%bin
>xjc.exe -p com.package example_schema.xsd

Step 3: Read XML and Unmarshal using JAXB.

Step 4: Generate required output using java.

The above solution is time consuming and screwed up my time.

Solution 2: XML –> DOM Object –> Manipulate data
Using simple DOM solved the issue quickly. This is the best route, when xsd is not available.
http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
-o-