请注意,这是使用Java API的Scala代码。在阅读了文档和示例之后,我已经能够提出这个从流连接中获取XML文档的解决方案:
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?
}
我知道我需要遍历解析器。但是我如何提取实际文件呢?我只需要文档字符串,以便将其传递给离线处理。
谢谢!
我在想做类似的事情:
while(parser.hasNext) {
println(parser.next)
}
但问题是上面返回一个布尔值。有什么方法可以制作文件吗?
答案 0 :(得分:1)
你使用'peak()'方法; 请参考我的java代码。 也许,很容易更改scala代码 祝你好运
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);
}
}
}
}
}