xml parsing in android from local file - android

I parsed xml data successfully several times before, however its my first time doing the same in android. I tried using DOM as I usually do however an error occurs on the .parse method each time. I searched online and tried multiple times however without any success. All I need to do is get xml data from a local file to put as arguments in some functions. I implemented the code in the Main Activity's onCreate method. This is what I usully do, however this time without any success:
try {
File xmlFile = new File("C:\\Users\\gg90\\Desktop\\testingxml.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
Hope you can help me out. Thanks!

There is no notion of a drive C: in android, so I guess your file is invalid and the parser chokes on it. Android uses a unix file system, so path look like /data/file.xml and so on.
To parse an xml file in the assets folder, have a look at this code, which opens the folder, gets the file and opens an input stream. And then calls this method.

1./ in res, create new folder: raw == /res/raw
copy file testingxml.xml and paste to folder raw
2./ parse XML from the location above by using SOM (ou SAX if you want)
InputStream catDoc = context.getResources().openRawResource(R.raw.testingxml);
//Using factory get an instance of document builder
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = builder.parse(catDoc, null);

Try creating a folder named raw in the res folder and put the xml file there through your project in workspace. Refresh the project until it is updated in R.java. Then use this code:
InputStream file = this.getResources().openRawResource(R.raw.license_status);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();

so go to your project folder and find RES folder then make a new folder there named "RAW"
and place your XML file there and refresh the project until it is updated in automatically generated R.java as a class.
Now you can use R.RAW.XYZ.xml ... :)

Related

Getting data from XML in android studio

My aim is to access the xml file and get the No present inside the xml file.
I want access data from my xml which is in local storage but i am not able to access the values getting errors at xpath.Kindly help me
xml file:
<?xml version="1.0" encoding="utf-8"?>
<Sample>
<Sample1>
<NO>257</LastPage>
</sample1>
<Sample2>
<NO>257</LastPage>
</sample2>
</Sample>
Class File:
AssetManager manager = getAssets();
InputStream inputStream = manager.open("PageDetails.xml");
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(inputStream);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/Bhajans/"+bookPath;
Node lastpageNO = (Node) xPath.evaluate(expression, xmlDocument,
XPathConstants.NODE);
Log.d("Displaying page No:","number"+lastpageNO);
Error:
06-06 12:10:04.119 30072-30072/com.com.sample.samples W/System.err﹕ javax.xml.xpath.XPathExpressionException: javax.xml.transform.TransformerException: Extra illegal tokens: '5'
06-06 12:10:04.119 30072-30072/com.com.sample.samples W/System.err﹕ at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:295)
You need to create xml parser as suggested in this tutorial
xml parser android
Also you can create xml file under xml directory of android folder structure. The xml directory would be parallel to res folder. You need to create this file manually. And then you can excess R>xl.yourfile or your constant.
And the xml you pasted has syntactical error.
The correct xml should be:
<Sample>
<Sample1>
<NO>257</No>
</sample1>
<Sample2>
<NO>257</No>
</sample2>
</Sample>

What is the default directory of android apps XML?

im using this code, and I think this code is for desktop apps
String filepath = "C:\\assets\\level\\\levelStatus.lvl";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
I was wondering if is this okay, or if not I think i need the directory of where will the XML files of my app are installed. Because I have tons of XML files in my assets folder
This will take you to the root of you assets folder:
file:///android_assets/
you can try something like that
InputStream is = getResources().getAssets().open("test.xml");
if your file have inner folder in assets folder then try this way
AssetManager am = getAssets();
InputStream is = am.open(file:///android_asset/myfoldername/test.xml);
or try like this
InputStream is = getResources().getAssets().open("myfoldername/test.xml");

How to open and edit an XML file from res/xml local project folder

I can open the xml files from my local folder of an android project in Eclipse to read the values:
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.tittes);
But how could I open a local xml file to edit the file and save it after?
Thanks for the replies!.,
I mean with a local file, a XML file I need to read and edit for data storage purposes. I've decided to place the file in the asset folder and I can open it easily for read::
*DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
InputStream iS = this.getAssets().open("myFile.xml");
Document doc = docBuilder.parse(iS);*
...,, but I don`t obtain, after many attemps, the way to save the file to edit: My last attempt is:
*TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
OutputStream f0;
byte buf[] = xmlString.getBytes();
**f0 = new FileOutputStream("/assets/wines.xml");**
//f0 = new FileOutputStream("file:///assets/wines.xml");
for(int i=0;i<buf .length;i++) {
f0.write(buf[i]);
}
f0.close();
buf = null;*
and the failed result is File not found!!!,. I come from C# projects,.and I couldn`t imagine that save a modified file was so dificult,.,
any ideas?!¿!? thanks again!!
but anyone know how could I open a local xml file to edit the file and save it after.
If by "local xml file" you mean a file in getFilesDir(), use DOM, or SAX, or the XmlPullParser.
If by "local xml file" you mean a resource, and you want to modify that resource, that is not possible at runtime.
There is no way to edit xml resources in the res folder in your program.
You can try another way, such as saving your resources to SharedPreference or SQLite at the first time your app starts, and later on you just edit and use your own copy.
This is useful when you use the resource to fill some component, but not good for layouts.

Android File Not Found Exception

I am writing an android app and I am having a very frustrating issue.
I have some data stored in an XML file called "ouritems.xml" in a "data" folder.
I have this code that is supposed to read from this file.
try {
File fXmlFile = new File("data/ouritems.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
nList = doc.getElementsByTagName("item");
}
catch(Exception e){
e.printStackTrace();
}
I have tried running this code in a plain java app, and it works perfectly.
However, when I try to run the android app I get a "File not found exception".
The file is stored in the app folder. And I CANNOT understand why it cannot be found.
Is this some sort of android permission problem??
I have actually resolved this issue. I put the file in a res/raw folder. This is the only way I could actually save the file in a way Android could read form it. (The phone I am testing on, doesn't even have an SD card.). I then read it by calling getResources().openRawResource(R.raw.ouritems). Thank you for putting me on the right path!
And I hope this can be helpful to someone else.
You will need to properly specify the full path to the file. Is the file on the SD card? In the apk raw asset folder? The File path you are using is a relative path that assumes a certain working directory which is not guaranteed to be what you think it is on Android.
You should specify an absolute path, not a relative one. What is the absolute path to the file on the Android system you are testing on?
you can't give absolute path to your src like C:\users.... your apk will be installed inside the sandbox area. /data/data is the path. if you have a package eg com.example.test then your path will be /data/data/com.example.test/ give your path as /data/data/ouritems.xml. if you have a package give accordingly.
If your xml file is in SD card you can use
File fXmlFile = new File(Environment.getExternalStorageDirectory()+"/ouritems.xml");
Thanks
Deepak

How to parse a local xml file using dom in android?

I have seen lots of examples about parsing local xml files with Sax but i need to do this with DOM. My xml file is under res/xml folder. Here is the code:
InputStream in = getResources().openRawResource(R.xml.maps);
StringBuffer str = new StringBuffer();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
Document document = db.parse(in, null);
document.getDocumentElement ().normalize ();
But it doesnt work. I think something missing with the line InputStream. It is really important for me, i need your help.
I had the same. I was wondering why this openRawResource gets the XML file corrupted, and that's because it was placed in r.xml.* not in r.raw.* :)
I have solved the problem. Just need to change small thing:
InputStream in = this.getResources().openRawResource(R.raw.bu);
I added "this" to that line and also I have put the maps.xml file under res/raw.

Categories

Resources