[英]How to read same XML file more times using XMLStreamReader
我分三個階段閱讀xml文件,在每個階段,我都對基於輸入參數的不同元素感興趣。
使用XMLStreamReader多次讀取一個xml文件的最佳方法是什么?
xmlInputFactory = XMLInputFactory.newInstance();
try {
XMLStreamReader streamReader xmlInputFactory.createXMLStreamReader(inputStream);
try {
while (streamReader .hasNext()) {
其中inputStream是FileInputStream實例
此刻,當我開始第二階段讀取時,我得到流關閉異常或streamReader.hasNext()為false。
將文件加載到內存中並使用ByteArrayInputStream
File f = ...;
int len = (int)f.length(); // careful: If the life is over 4 gigs this won't work
byte myXML[] = new byte[];
FileInputStream fis = new FileInputStream(f);
int read = fis.read(f); // not guarenteed to read all bytes, but in my experience, this reads all bytes
if (read != len) throw RuntimeExcption("Didn't read everything");
// Now you can create as many XMLStreamReaders as you want like
try {
XMLStreamReader streamReader xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(buf));
如果要訪問的數據不是按順序排列的,則必須使用XMLStreamReader
對XML
3次遍歷。
如果您只想讀取一次,則可以將數據存儲在全局變量中,您可以在讀取過程中填充這些變量,從而使三個階段合為一體。
但是,如果您需要完成第一個階段以開始第二個階段, 我建議您使用JaxB
,它將在XSD
Schema的Java
對象中轉換XML
,從而更容易以非順序方式操作XML
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.