2013-11-01 107 views
1

我正在嘗試使用Stax解析開放街道地圖的XML結構。在我的實現中,我使用XMLStreamConstants.START_ELEMENTXMLStreamConstants.END_ELEMENT 來識別元素。使用STAX API進行XML解析

開放街道地圖結構具有元素如標籤其描述爲好節點,以及所述方式。這裏是一個結構的例子:

 <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> 

如果分析器讀取標籤元素,我該如何區分節點和方式?

回答

2

您可以使用節點表示的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