Problem loading and parsing xml from resources

I wrote a parser that parses an XML file from a from HttpURLConnection. It works great.

Problem: I need to rewrite this so that the xml file is downloaded from local resources and not from the Internet, but I cannot get this to work ... Just to give you an idea of โ€‹โ€‹what the original web parser looks like:

InputStream in=null; URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConnection.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(in); Element docEle = dom.getDocumentElement(); NodeList nl = docEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); //START PARSING...... 

Now I use the code that I use to try to parse the local resource hosted in xml / myfile.xml in the resources folder:

 InputStream in=null; in = mParentActivity.getResources().openRawResource(R.xml.myfile); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(in); // THIS IS WHERE I GET AN SAXParseException Element root = dom.getDocumentElement(); NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); //START PARSING...... 

The local xml file and the web file are exactly the same ... If someone looks at it: http://agens.no/Eniro/Android/SEWheel/Category2.plist.xml

And heres stacktrace: 02-01 16: 08: 45.546: WARN / System.err (19703): org.xml.sax.SAXParseException: name expected (position: START_TAG @ 1: 309 in java.io.InputStreamReader@47668728 )

Indicate all the help :)

+1
source share
1 answer

Found the answer. When the file was in the res / xml folder, the input stream showed a lot of invalid characters. When I put it in the res / raw folder, it worked fine.

+1
source

Source: https://habr.com/ru/post/1309527/


All Articles