Sax-разбор локального XML-файла в Android - PullRequest
0 голосов
/ 30 ноября 2011

я хочу разобрать страну она присутствует в папке xml

<My_location_country>
    <Country_str_code>AW</Country_str_code>
    <Country_str_name>Aruba</Country_str_name>
</my_location_country>

....................... я хочу отобразить название страны в адаптере массива, когда я выбираю страну, я хочу, чтобы код страны печатался, я использую следующий метод, но он не работает

                   try {

                        SAXParserFactory factory = SAXParserFactory.newInstance();
                        SAXParser saxParser = factory.newSAXParser();

                        DefaultHandler handler = new DefaultHandler() {

                        boolean countryflag = false;
                        boolean countryidflag = false;


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

                            System.out.println("Start Element :" + qName);

                            if (qName.equalsIgnoreCase("Country_str_code")) {
                                countryidflag = true;
                            }

                            if (qName.equalsIgnoreCase("Country_str_name")) {
                                countryflag = true;
                            }


                        }

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

                            System.out.println("End Element :" + qName);

                        }

                        public void characters(char ch[], int start, int length) throws SAXException {

                            if (countryidflag) {
                                System.out.println("Country_str_code" + new String(ch, start, length));
                                String val=new String(ch, start, length);

                                countryid.add(val);
                                countryidflag = false;
                            }

                            if (countryflag) {
                                System.out.println("Country_str_name " + new String(ch, start, length));
                                String val1=new String(ch, start, length);
                                countryname.add(val1);

                                countryflag = false;
                            }
                     }

                         };

                         File file = new File("res/xml/country.xml");
                         InputStream inputStream= new FileInputStream(file);
                         Reader reader = new InputStreamReader(inputStream,"UTF-8");

                         InputSource is = new InputSource(reader);
                         is.setEncoding("UTF-8");
                           //saxParser.parse();
                         } catch (Exception e) {
                           e.printStackTrace();
                         }

в расположении файла я получаю ошибку любая помощь .............. спасибо заранее

Ответы [ 2 ]

1 голос
/ 30 ноября 2011

Пожалуйста, используйте правильный путь к файлу

вы можете поместить файл XML в папку raw или папку активов

для сырой папки вы можете получить файл как

int resourceId = context.getResources().getIdentifier("com.your.package:raw/somefile.xml");
File f = new File(context.getResources().openRawResource(resourceId));

или

 InputStream in = this.getResources().openRawResource(R.raw.myxml); 

из набора

AssetManager assetManager = getAssets();
inputStream = assetManager.open("readme.xml")

с SDCard

FileInputStream in = new FileInputStream("/sdcard/text.txt");

// для файлов ресурсов и хранилища SD CARD, используйте полную ссылку для вас Это

this2

0 голосов
/ 23 декабря 2011
try  
{  
    //Read myxml.xml file from /res/raw folder  
    InputStream is=getResources().openRawResource(R.raw.country);  

    Log.i("TAG","is value==>"+is);  
    DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();  
    Document doc=builder.parse(is, null);  

    //get the root node   
    NodeList nodeList=doc.getElementsByTagName("skadate_location_country");  

    Log.i("TAG","nodeList Length --" + nodeList.getLength()); //output:- -1  
    Log.i("TAG","nodeList name --" + nodeList.item(0).getNodeName()); //output:- message  
    for(int j=0; j<nodeList.getLength(); j++) {
       Node nodee=nodeList.item(j); 
       for(int i=0;i<nodee.getChildNodes().getLength();i++)
       {  
           Node node=nodee.getChildNodes().item(i);  
           if(node.getNodeName().equalsIgnoreCase("Country_str_code")){  
               Log.i("TAG","from node::" + node.getTextContent()); 
               countryname.add(node.getTextContent());
               countrySelector.setAdapter(countryname);
               countrySelector.setOnItemSelectedListener(this); 
           }  
           else if(node.getNodeName().equalsIgnoreCase("Country_str_name")){  
               Log.i("TAG","to node::" + node.getTextContent());  
           }  
       }
    }
    is.close();  
} catch(Exception e) {  
   System.out.println("ERROR while parsing xml:----" + e.getMessage());  
}
...