Shwe Min
Shwe Min

Reputation: 15

How parse XML from sd card for android app?

I have xml file this format from sd card.

<consignments creationDate="2015-05-11 08:04:38">
 <consignment iid="142435846">
  <consignmentId>194556772</consignmentId>
  <orderCode>MUC-EC-4556772</orderCode>
  <pickupDate>2015-04-01</pickupDate>
  <referenceConsignor>236847.1</referenceConsignor>
  <consignorCountry>DE</consignorCountry>
  <consignorZip>83125</consignorZip>
  <consignorCity>EGGSTAETT</consignorCity>

</consignment>

how to read this xml file from sd card and show result all items into textview?

Upvotes: 2

Views: 424

Answers (2)

Ram
Ram

Reputation: 1428

like this you can parse.

 try {
     File file = new File("mnt/sdcard/xxx.xml");
     InputStream is = new FileInputStream(file.getPath());
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(new InputSource(is));
     doc.getDocumentElement().normalize();

     NodeList nodelist = doc.getElementsByTagName("consignment");
     Node node = nodeList.item(0);
     Element fstElmnt = (Element) node;
     String id=fstElmnt.getAttribute("iid");
     String consignmentId=(String)fstElmnt.Element("consignmentId");
     String orderCode=(String)fstElmnt.Element("orderCode");

    }
    catch (Exception e) 
    {
     System.out.println("XML Pasing Excpetion = " + e);
    }

Upvotes: 1

asu
asu

Reputation: 11

To pass your file in to be read you will need to do first get your file:

String sdcardDir = Environment.getExternalStorageDirectory().getAbsolutePath;
File fileToRead = new File(dir, "path/to/file");
InputStream stream = new FileInputStream(fileToRead);

See the following site on how to parse XML: http://developer.android.com/training/basics/network-ops/xml.html

With the inputstream you can now pass it to your parser from the link.

EDIT: You can add it to your textview by adding it to your layout then in your activity/fragment find the view and call .setText(String).

Upvotes: 0

Related Questions