2017-03-07 240 views
1

是否可以在SAX解析器中提供路徑表達式?我有一個XML文件,它具有幾個相同的名稱標籤,但它們位於不同的元素中。有什麼辦法可以區分它們嗎?下面是XML:使用SAX解析器,如何解析java中的xml文件

<report id="322077"> 
     <update> 
      <when>1136117311</when> 
      <what>[email protected]</what> 
     </update> 
     <update> 
      <when>1136117422</when> 
      <what>[email protected]</what> 
     </update> 
     </report> 
    <report id="322074"> 
     <update> 
      <when>1136117311</when> 
      <what>[email protected]</what> 
     </update> 
     <update> 
      <when>1136117422</when> 
      <what>[email protected]</what> 
     </update> 
     </report> 
    <report id="322076"> 
     <update> 
      <when>1136117311</when> 
      <what>[email protected]</what> 
     </update> 
     <update> 
      <when>1136117422</when> 
      <what>[email protected]</what> 
     </update> 
     </report> 
+0

請參閱http://stackoverflow.com/questions/1863250/is-there-any-xpath-processor-for-sax-model – rpfun12

+0

這是必須使用一個SAX解析器?如果首先將它讀入DOM,瀏覽結構會更容易。然後,您可以使用許多實用方法來搜索和處理節點。 – sprinter

+0

不是必須使用SAX解析器。我怎樣才能做到這一點 – sudo

回答

0
String xml= // your xml 
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
Document document = builder.parse(new InputSource(new StringReader(xml))); 
String expression="//update"; // See XPath 
XPathExpression expr = xpath.compile(expression) ; 
    NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); 
for (int k = 0; k < nodes.getLength(); k++) { 
// Do what you want with that