您可以使用節點表示的ArrayDeque
,或者如果層次結構的深度很小,甚至可以構建臨時的類DOM結構。
下面是與ArrayDeque
一個例子...
假設stuff.xml
命名這個XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<stuff>
<node id="2311741639" lat="50.7756648" lon="6.0844948">
<tag k="entrance" v="yes"/>
</node>
<way id="4964449" visible="true" uid="67862">
<nd ref="27290865"/>
<tag k="highway" v="residential"/>
</way>
</stuff>
假設該文件是在路徑:/my/path/
下面是代碼(try/catch語句Java 6樣式):
InputStream is = null;
XMLStreamReader reader = null;
try {
is = new FileInputStream(new File("/my/path/stuff.xml"));
XMLInputFactory xif = XMLInputFactory.newInstance();
reader = xif.createXMLStreamReader(is);
ArrayDeque<String> nodes = new ArrayDeque<String>();
while (reader.hasNext()) {
int current = reader.next();
switch (current) {
case XMLStreamConstants.START_ELEMENT: {
nodes.add(reader.getLocalName());
System.out.println("START: " + nodes.getLast());
if (nodes.size() > 1) {
Iterator<String> iterator = nodes.descendingIterator();
// skipping first one as it's already represented
iterator.next();
while (iterator.hasNext()) {
System.out.println("\t in " + iterator.next());
}
}
break;
}
case XMLStreamConstants.END_ELEMENT: {
System.out.println("END: " + nodes.removeLast());
Iterator<String> iterator = nodes.descendingIterator();
while (iterator.hasNext()) {
System.out.println("\t in " + iterator.next());
}
break;
}
}
}
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
catch (XMLStreamException xse) {
xse.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
is.close();
}
catch (XMLStreamException xse) {
xse.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
輸出:
START: stuff
START: node
in stuff
START: tag
in node
in stuff
END: tag
in node
in stuff
END: node
in stuff
START: way
in stuff
START: nd
in way
in stuff
END: nd
in way
in stuff
START: tag
in way
in stuff
END: tag
in way
in stuff
END: way
in stuff
END: stuff