Android XML parse failed Unexpected token - android

In my app(game), i need to read a XML script and turn in into a class object; i've completed the entire XML reader via DOM
but when i run , i got the following error:
05-08 23:03:22.342: I/System.out(588): XML Pasing Excpetion = org.xml.sax.SAXParseException: Unexpected token (position:TEXT ��������������������...#1:69 in java.io.InputStreamReader#4129a200)
i've read some answers about this but they all failed to fix my problem (http://stackoverflow.com/questions/7885962/android-utf-8-file-parsing)..
here's my code:
InputStream inputStream = ctx.getResources().openRawResource(R.xml.script);
ctx.getApplicationContext().getPackageName()+"/xml/"+path);
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document root = db.parse(is);
according to the problem, i've also tried this to:
InputStream inputStream = ctx.getResources().openRawResource(R.xml.script);
Document root = db.parse(inputStream);
which produced exactly the same exceptions...
how to solve this problem?
my xml file:
<script>
<scene no="0">
<character id="1">1</character>
<dialog no="1">
<title>1</title>
Sub-Element 1
</dialog>
</scene>
</script>

Your XML is invalid. "Sub-Element 1" should be within an element itself.
XML-documents should also begin with a tag defining it as XML: <?xml version="1.0" ?> So your complete file would be:
<?xml version="1.0" ?>
<script>
<scene no="0">
<character id="1">1</character>
<dialog no="1">
<title>1</title>
<something_else>Sub-Element 1</something_else>
</dialog>
</scene>
</script>
Or you could use "Sub-Element" as the element name (instead of something_else) and 1 as the value.

Where do you store your xml file? In "res" folder. You should store it in "assets". Res-solution is not working because of specific of the "res" folder and it's presentation in the apk. Move your file to the "assets" and you'll see that everything is working.
Use the following code for creating InputSource
getAssets().open("yourfilename.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>

can't open xml file on android

I am working on an android application in which I want to parse an xml file as a local resource. I use jdom to parse it, but I have a probleme, I can not open the file and I don't know why. The error is at this line :
document = builder.build(new File("res/xml/data.xml"));
The file is located into the folder res/xml of my project. I got this error:
java.io.IOException: Couldn't open file:/res/xml/data.xml
Caused by java.io.FileNotFoundException :res/xml/data.xml
I tried this:
document = builder.build(new File("data.xml"));
but it did not work. I don't know why the file is not found.
Would you have an idea?
Thanks in advance
Thank you for your suggestion. The 'Uri path' works but not the line
document = builder.build(new File(path));
The method class File must have a type entree String. I tried this:
document = builder.build(new File(path.getPath());
but it returned null and
document = builder.build(new File(path.toString());
I got the same error. Would you have an idea ?
Thanks in advance !!
I believe you will need to use an URI in your file constructor that points to the data.xml file.
Try something like this:
Uri path = Uri.parse("android.resource://my.package.here/" + R.xml.data);
document = builder.build(new File(path));
This tutorial here might also be helpful: http://androidbook.blogspot.com/2009/08/referring-to-android-resources-using.html
If this is a resource inside your application then you should use Resources methods suchas getXml(). You can get an instance of the rources class from the Context object
InputStream is = context.getResources().openRawResource(R.raw.data);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
document = builder.build(br);
Be sure to put the data.xml in the res/raw-folder.

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.

xml parsing in android from local file

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 ... :)

Why does this code keep triggering the SaxParseException : ""PI must not start with xml"?

This code is used to generate a XML document from its String representation. It works fine in my small unit tests, but fails in my actual xml data. The line where it triggers is Document doc = db.parse(is);
Any ideas?
public static Document FromString(String xml)
{
// from http://www.rgagnon.com/javadetails/java-0573.html
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document doc = db.parse(is);
doc.normalize();
return doc;
}
catch (Exception e)
{
Log.WriteError("Failed to parse XML", e, "XML.FromString(String)");
return null;
}
}
Thanks for your help everyone.
I discarded the <?xml version="1.0" encoding="utf-8"?> which cleared this error. Still don't understand what the reason for this might be, but it worked nonetheless.
I went on to find one of my buffered writers (when extracting from a zip file into memory) wasn't being flushed, which was causing the xml string to be incomplete.
Thanks everyone for your help!
You may check if your xml file has BOM header
I had the same problem while parsing XML generated by PHP.
After I added the ContentType header "text/xml" it works like a charm.
as #StaxMan said, remove any unknown characters before
responseBody = responseBody.substring(responseBody.indexOf("<"));
this issue will be caused too by having the line < ?xml version="1.0" encoding="UTF-8"?> together with the xml data in the same line...
< ?xml version="1.0"
encoding="UTF-8"?>< secciones>< seccion>< id>0< /id>< nombre>Portada< feedURL>http://iphone.elnorte.com/libre/online07/a
....
You should have checked the encoding of the file instead of discarding the xml line.
I have found that my Eclipse (on Windows) had the same problem with a resource encoded as Unix-U8. After converting it to DOS-U8, the error went away.

Categories

Resources