Skip to content

Instantly share code, notes, and snippets.

@raphw
Last active February 8, 2017 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/269e8859706362a2ea87e7a59400d010 to your computer and use it in GitHub Desktop.
Save raphw/269e8859706362a2ea87e7a59400d010 to your computer and use it in GitHub Desktop.
XML Stream sample
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLOutputFactory xof = XMLOutputFactory.newFactory();
try (InputStream in = new FileInputStream("/home/rafael/foo.xml")) {
XMLEventReader xer = xif.createXMLEventReader(in);
XMLEventWriter xew = xof.createXMLEventWriter(System.out);
JAXBContext jc = JAXBContext.newInstance(Bar.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
while (xer.hasNext()) {
if (!xer.peek().isCharacters() || !xer.peek().asCharacters().isWhiteSpace()) {
if (xer.peek().isStartElement() && xer.peek().asStartElement().getName().getLocalPart().equals("bar")) {
Bar bar = (Bar) unmarshaller.unmarshal(xer);
bar.qux = "abc";
marshaller.marshal(bar, xew);
} else {
xew.add(xer.nextEvent());
}
} else {
xer.nextEvent();
}
}
xer.close();
xew.close();
}
System.out.flush();
XMLInputFactory xif = XMLInputFactory.newFactory();
JAXBContext jaxbContext = JAXBContext.newInstance(Bar.class);
String rootTag = "foo";
try (InputStream in = Main2.class.getResourceAsStream("/foo.xml")) {
XMLStreamReader xer = xif.createXMLStreamReader(in);
if (xer.nextTag() != XMLStreamConstants.START_ELEMENT) {
throw new IllegalStateException("1");
} else if (!xer.getName().getLocalPart().equals(rootTag)) {
throw new IllegalStateException("2");
}
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
while (xer.nextTag() == XMLStreamConstants.START_ELEMENT) {
Bar bar = (Bar) unmarshaller.unmarshal(xer);
System.out.println(bar.qux);
}
if (!xer.getName().getLocalPart().equals(rootTag)) {
throw new IllegalStateException("3");
}
while (xer.hasNext()) {
if (xer.next() == XMLStreamConstants.START_ELEMENT) {
throw new IllegalStateException("4");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment