想必你的意圖是要做到這一點與Android的API,所以請酌情翻譯。
在常規Java,存在XmlStreamReader
爲StAX的解析,並且它可與InputStream
從被實例化,像這樣:
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
public class ParseStream {
public static void main(String[] args) throws Exception {
URLConnection connection =
new URL("http://api.androidhive.info/pizza/?format=xml").openConnection();
InputStream inputStream = connection.getInputStream();
XMLStreamReader streamReader =
XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "UTF-8");
while (streamReader.hasNext())
if (streamReader.next() == XMLStreamConstants.START_ELEMENT)
System.out.println("START_ELEMENT " + streamReader.getName());
}
}
事實上我會有所改進它,例如從URLConnection中獲得編碼,而不是使用固定的編碼。
但它應該給出這個想法。