如何在Android中使用pull解析器解析XML

时间:2012-09-20 03:14:56

标签: android parsexml

我有XML:

    <?xml version="1.0" encoding="UTF-8"?>
          <categories type="array">
               <category>
                    <category_id>8</category_id>
                    <category_name>Công Nghệ  & Xe</category_name>
                    <category_code>cong-nghe-xe</category_code>
                    <subcategory>
                         <category_id>59</category_id>
                         <category_name>Kiến trúc - thủ thuật</category_name>
                         <category_code>cong-nghe-xe_kien-thuc-thu-thuat</category_code>
                    </subcategory>
                    .................................................
               </category>
               ................................................. 
          </categories>

如何在Android中阅读并填充ListView,我该怎么办:DOM,XML Parser或SAX ??

2 个答案:

答案 0 :(得分:0)

对于像这样的小小片段,我更喜欢DOM。

String xml;
Document doc;
Element root = null;
try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    doc = builder.parse( new InputSource( new StringReader( xml ) ) );
    root = doc.getDocumentElement();
} catch ( Exception e ) {
    // do something
}

if( root != null ) {
    NodeList cats = root.getElementsByTagName( "category" );
    for( int i=0; i < cats.getLength(); i++ ) {
    Element category = (Element)cats.item( i );
        ....
    }
}

答案 1 :(得分:0)