Parsing XML file stored in internal storage using DOM parser in android.

4.7k Views Asked by At

I have created an xml file in the device's internal storage as described on the android developers website. I now want to parse the file using DOM parser. What do i need to do to make the DOM parser read my XML file?? Here's a snippet:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse(new InputSource(new StringReader(data)));
    dom.getDocumentElement().normalize(); 

What do i need to put in the place of "data" in:

    Document dom = db.parse(new InputSource(new StringReader(data)));

I know it's silly but any help would be appreciated.

4

There are 4 best solutions below

1
On BEST ANSWER

You can make a input stream of the xml string like below and then getting nodes you can parse to get values.

InputStream is = new ByteArrayInputStream(theXMLString.getBytes("UTF-8"));

        // Build XML document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);

Remember you are passing xml file as a string.

4
On

You can give FileInputStream in inputsource

Document dom = db.parse(new InputSource(new FileInputStream(data)));

2
On

For reading XML file, you should try below

FileInputStream in = new FileInputStream("/sdcard/text.txt");
StringBuffer data = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);

BufferedReader inRd = new BufferedReader(isr);

String text;
while ((text = inRd.readLine()) != null) {
    inLine.append(text);
    inLine.append("\n");
}
in.close();

String finalData =data.toString();  // Here is your data.

Hope above may useful to you.

0
On

Try this code for parsing from Asset folder using DOM Parser :

    DocumentBuilderFactory DBF;
    DocumentBuilder DB;
    Document dom;
    Element elt;

    DBF = DocumentBuilderFactory.newInstance();
    DB = DBF.newDocumentBuilder();
    dom = DB.parse(new InputSource(getAssets().open("city.xml")));
    elt = dom.getDocumentElement(); 
    NodeList items = elt.getElementsByTagName("item");

where item is Node element, add try ctch block as per the requirements.