Reputation: 13320
Note this is Scala code using Java APIs. After reading the docs and examples, I've been able to come up with this solution that grabs an XML Document from a streaming connection:
val connection = getConnection(URL, USER, PASSWORD)
val inputStream = connection.getInputStream()
val factory = XMLInputFactory.newInstance()
val parser = factory.createFilteredReader(factory.createXMLStreamReader(inputStream), new XMLDocFilter())
while(parser.hasNext){
// what to do?
}
I understand that I need to iterate through the parser. But how would I extract the actual document? All I need is the document string so I can pass it to offline processing.
Thanks!
I've been following: http://www.java-tips.org/java-ee-tips/enterprise-java-beans/introducing-the-sun-java-streaming-xml-p.html
I was thinking of doing something like:
while(parser.hasNext) {
println(parser.next)
}
But the problem is that the above returns a boolean. Any way to make that the document?
Upvotes: 0
Views: 160
Reputation: 1179
you use 'peak()' method; Please refer to my java code. maybe, easy to change the scala code Good Luck
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import org.xml.sax.SAXException;
public class DomParserMain {
final static String ROOT_NODE_NAME = "data";
final static String FILE_PATH = "/Users/file.xml";
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, JAXBException, XMLStreamException, XPathExpressionException, TransformerException {
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLEventReader xmlr = null;
xmlr = xif.createXMLEventReader((new FileInputStream(new File(FILE_PATH))));
boolean inline = false;
StringBuffer sb = new StringBuffer(1024 * 66);
while(xmlr.hasNext()){
XMLEvent event = xmlr.nextEvent();
if (event.isStartElement() ){
StartElement element = (StartElement) event;
if( ROOT_NODE_NAME.equals( element.getName().toString().trim() ) ) {
inline = true;
}
}
if(inline) {
sb.append( xmlr.peek() );
}
if (event.isEndElement() ){
EndElement element = (EndElement)event ;
if( ROOT_NODE_NAME.equals( element.getName().toString().trim() )) {
inline = false;
System.out.println("=====");
System.out.println(sb.toString());
System.out.println("=====");
sb.setLength(0);
}
}
}
}
}
Upvotes: 1