2014-02-26 149 views
1

我通過SAX XML解析器解析一個簡單的XML文件,並在列表視圖中顯示結果。這已經成功完成了。現在我想在abc標籤像下面的XML文件一樣關閉時執行此操作。然後下面的標籤項不解析(蘋果不添加在列表視圖中)。誰能幫我。 Thanx提前SAX拉解析器Android

<abc> 
    <employee> 
    <name>Android</name> 
    </employee> 
    <employee> 
    <name>Nokia</name> 
    </employee> 
</abc> 
    <employee> 
    <name>Apple</name> 
    </employee> 

這是SAXXMLHandler我使用

public class SAXXMLHandler extends DefaultHandler { 

    private List<Employee> employees; 
    private String tempVal; 
    private Employee tempEmp; 

    public SAXXMLHandler() { 
     employees = new ArrayList<Employee>(); 
    } 

    public List<Employee> getEmployees() { 
     return employees; 
    } 

    // Event Handlers 
    public void startElement(String uri, String localName, String qName, Attributes attributes) 
      throws SAXException { 
     // reset 
     tempVal = ""; 

     if (qName.equalsIgnoreCase("employee")) { 
      // create a new instance of employee 
      tempEmp = new Employee(); 

     } 
    } 

    public void characters(char[] ch, int start, int length) throws SAXException { 
     tempVal = new String(ch, start, length); 
    } 

    public void endElement(String uri, String localName, String qName) throws SAXException { 

     if (qName.equalsIgnoreCase("employee")) { 
      // add it to the list 
      employees.add(tempEmp); 
     } else if (qName.equalsIgnoreCase("name")) { 
      tempEmp.setName(tempVal); 
     } 
    } 
} 
+0

這是你自己創建的xml嗎? –

+0

是啊從資產文件夾中加載xml – vik

+0

這不是很好形成....我給你解決方案的答案。 –

回答

1

保持一個boolean來控制哪些員工名字應該添加到列表中,那些不應該......下面......

public class SAXXMLHandler extends DefaultHandler { 

    private List<Employee> employees; 
    private String tempVal; 
    private Employee tempEmp; 

    private boolean shouldAdd = false; 

    public SAXXMLHandler() { 
     employees = new ArrayList<Employee>(); 
    } 

    public List<Employee> getEmployees() { 
     return employees; 
    } 


    public void startElement(String uri, String localName, String qName, Attributes attributes) 
      throws SAXException { 

     tempVal = ""; 

     if (qName.equalsIgnoreCase("abc")) { 

      shouldAdd = true; 

     } else if (qName.equalsIgnoreCase("employee")) { 
      // create a new instance of employee 
      tempEmp = new Employee(); 

     } 
    } 

    public void characters(char[] ch, int start, int length) throws SAXException { 
     tempVal = new String(ch, start, length); 
    } 

    public void endElement(String uri, String localName, String qName) throws SAXException { 

     if (qName.equalsIgnoreCase("abc") && shouldAdd == true) { 

      shouldAdd = false; 

     } else if (qName.equalsIgnoreCase("employee") && shouldAdd == true) { 
      // add it to the list 
      employees.add(tempEmp); 
     } else if (qName.equalsIgnoreCase("name")) { 
      tempEmp.setName(tempVal); 
     } 
    } 
} 
+0

你不明白我需要什麼。我需要添加項目直到abc標籤關閉。之後沒有更多的項目被添加到列表視圖中。這可能嗎?或者我爲此使用其他解析器? – vik

+0

看到我更新的答案...可能是這是你想要做的。 –

+1

非常感謝你,它的工作 – vik