ノード表現の を使用しArrayDeque
たり、階層の深さが小さい場合は一時的な DOM のような構造を構築したりすることもできます。
ここに例がありArrayDeque
ます...
という名前のこの XML ファイルを想定しますstuff.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