0

请注意,这是使用 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?
  }

我知道我需要遍历解析器。但是我将如何提取实际的文档呢?我只需要文档字符串,以便将其传递给离线处理。

谢谢!

编辑

我一直在关注:http ://www.java-tips.org/java-ee-tips/enterprise-java-beans/introducing-the-sun-java-streaming-xml-p.html

我正在考虑做类似的事情:

while(parser.hasNext) {
  println(parser.next)
}

但问题是上面返回一个布尔值。有什么办法可以使该文件?

4

1 回答 1

1

您使用“峰值()”方法;请参考我的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);
                }
            }
        } 
    }
}
于 2013-07-11T08:07:40.147 回答