13

I want to read xml file which looks like the following ... I have stored it in assets folder with

<ImageList SpriteSheetName="hh_gmw01">
   <Image Name="gmw01"     x="0" y="0" width="1047" height="752"/>
   <Image Name="hht1l01"   x="388" y="269" width="34" height="36"/>
   <Image Name="hht1l02"   x="147" y="99" width="85" height="33"/>
</ImageList>

How do I get these values?

Rui Carneiro
  • 5,595
  • 5
  • 33
  • 39
user1169079
  • 3,053
  • 5
  • 42
  • 71
  • http://www.google.co.in/#hl=en&output=search&sclient=psy-ab&q=java+read+xml+file&pbx=1&oq=java+read+xml+file&aq=f&aqi=&aql=&gs_sm=3&gs_upl=999l5493l0l5744l18l14l0l0l0l0l0l0ll0l0&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=f56754703660b899&biw=1353&bih=1070 – Samir Mangroliya Feb 27 '12 at 11:20

6 Answers6

8

Try this out first:

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

Button btn;
TextView tvXml;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn = (Button) findViewById(R.id.button1);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Load XML for parsing.
            AssetManager assetManager = getAssets();
            InputStream inputStream = null;
            try {
                inputStream = assetManager.open("textxml.xml");
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }

            String s = readTextFile(inputStream);
            TextView tv = (TextView)findViewById(R.id.textView1);
            tv.setText(s);
        }
    });
}


private String readTextFile(InputStream inputStream) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte buf[] = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {

    }
    return outputStream.toString();
}
}
Shishir Shetty
  • 2,021
  • 3
  • 20
  • 35
4

There is several ways to read a XML in Android. My first option is DocumentBuilder since do not create an API version restriction (is available since API Level 1).

An example from one of my projects:

public Document parseXML(InputSource source) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(source);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
 }

How do you read the file and access the document values after this, well, its pretty basic, just Google it.

Rui Carneiro
  • 5,595
  • 5
  • 33
  • 39
2
/*
* <ImageList SpriteSheetName="hh_gmw01">
*       <Image Name="gmw01"     x="0" y="0" width="1047" height="752"/>
*       <Image Name="hht1l01"   x="388" y="269" width="34" height="36"/>
*       <Image Name="hht1l02"   x="147" y="99" width="85" height="33"/>
* </ImageList>
*/

private void testXML() throws XmlPullParserException {
    AssetManager assetManager = getAssets();
    try {
        InputStream xmlStream = assetManager.open("xmlfile.xml");
        try {
            XmlPullParser xmlParser = Xml.newPullParser();
            xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            xmlParser.setInput(xmlStream, null);
            xmlParser.nextTag();

            int imgNum = 0;
            xmlParser.require(XmlPullParser.START_TAG, null, "ImageList"/*root node*/);
            Log.d("ImageList", "SpriteSheetName = " + xmlParser.getAttributeValue(null, "SpriteSheetName"));
            while (xmlParser.next() != XmlPullParser.END_TAG) {
                if (xmlParser.getEventType() != XmlPullParser.START_TAG) {
                    continue;
                }

                xmlParser.require(XmlPullParser.START_TAG, null, "Image");
                //. fetch nodes attributes here...
                Log.d("xmlNode", "img " + (++imgNum) +
                           " Name = " + xmlParser.getAttributeValue(null, "Name") +
                        " x = "       + xmlParser.getAttributeValue(null, "x") +
                        " y = "       + xmlParser.getAttributeValue(null, "y") +
                        " width = "   + xmlParser.getAttributeValue(null, "width") +
                        " height = "  + xmlParser.getAttributeValue(null, "height")
                );
                //................................
                xmlParser.nextTag();
                xmlParser.require(XmlPullParser.END_TAG, null, "Image");
            }


        } finally {
            xmlStream.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    assetManager.close();
}
tdjprog
  • 706
  • 6
  • 11
2

To start with use DOM parser. Since its much lesser code, and easy to follow. SAX parser is just too much code to start with. People will argue that SAX is faster, yes it is, but DOM is easier, lesser code and lesser bugs.

If you must move to SAX, first measure your response times when using DOM, and only if parsing is causing you the most pain, then move to SAX. Or else DOM does a wonderful job.

Sears India
  • 210
  • 1
  • 6
1

Personally i wouldn't recommend the DOM parser, try this instead, simple annotations can help you by using the Simple xml parser

http://www.javacodegeeks.com/2011/02/android-xml-binding-simple-tutorial.html

Some one Some where
  • 777
  • 1
  • 8
  • 26
-1

Try this for Xamarin.Android (Cross Platform)

you need to store xml file into Assets folder with build action "AndroidAsset".

using System;
using System.Xml;
using System.IO;

Code snippet to read xml file

XmlDocument xDoc = new XmlDocument();
Stream xmlStream = Assets.Open("textxml.xml");
xDoc.Load(xmlStream);

XmlDocument class implements the core XML Document Object Model (DOM) parser for the .NET Framework.

JJD
  • 50,076
  • 60
  • 203
  • 339
Nitin V. Patil
  • 185
  • 2
  • 2
  • Although the result is cross-platform, i'm not sure how wise it is in general to use dot net for Android apps; i've upvoted the answer now it's been edited and probably works (can't test it here, Xamarin isn't available for my computer system). – barefootliam Dec 05 '18 at 07:36