Last active
September 7, 2017 17:47
-
-
Save VenkataRaju/45917bbc99538eab5957 to your computer and use it in GitHub Desktop.
JAXB Partial Object Parsing
This file contains hidden or 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
public class JaxbPartialObjectParser | |
{ | |
public static void main(String[] args) throws Exception | |
{ | |
String xmlStr = "<root><student><name>Raju</name></student></root>"; | |
// Assuming Student class is JAXB generated | |
Iterator<Student> it = extractPartialObjects(new StringReader(xmlStr), QName.valueOf("student"), Student.class); | |
while (it.hasNext()) | |
System.out.println(it.next().getName()); | |
} | |
/** | |
* @param partialObjClass | |
* JAXB generated class which needs to be created by start parsing | |
* from tag {@code partialObjTag} | |
*/ | |
public static <T> Iterator<T> extractPartialObjects(Reader reader, QName partialObjTag, Class<T> partialObjClass) | |
{ | |
XMLStreamReader xsr; | |
Unmarshaller unmarshaller; | |
try | |
{ | |
xsr = XMLInputFactory.newInstance().createXMLStreamReader(reader); | |
unmarshaller = JAXBContext.newInstance(partialObjClass).createUnmarshaller(); | |
} | |
catch (JAXBException | XMLStreamException | FactoryConfigurationError e) | |
{ | |
throw new RuntimeException(e.getMessage(), e); | |
} | |
return new Iterator<T>() | |
{ | |
T curPartialObj; | |
@Override | |
public boolean hasNext() | |
{ | |
return (curPartialObj != null) || ((curPartialObj = parseNextPartialObj()) != null); | |
} | |
@Override | |
public T next() | |
{ | |
if (!hasNext()) | |
throw new NoSuchElementException(); | |
T tmp = curPartialObj; | |
curPartialObj = null; | |
return tmp; | |
} | |
T parseNextPartialObj() | |
{ | |
try | |
{ | |
for (;; xsr.next()) | |
{ | |
if (xsr.getEventType() == XMLEvent.START_ELEMENT && xsr.getName().equals(partialObjTag)) | |
return unmarshaller.unmarshal(xsr, partialObjClass).getValue(); | |
if (!xsr.hasNext()) | |
break; | |
} | |
return null; | |
} | |
catch (XMLStreamException | JAXBException e) | |
{ | |
throw new RuntimeException(e.getMessage(), e); | |
} | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment