Tuesday, 13 August 2019

android - XML sax parser - ignore unbound prefix exception



When parsing an xml file in android, I'm doing like this:




try
{
InputStream is = ...
MyContentHandler ch = new MyContentHandler();
Xml.parse(is, Encoding.UTF_8, ch);
}
catch ...


The problem is that sometimes the file I'm trying to parse is not well-formed.

In my case, undeclared namespaces may be present.



The data I'm interested in is not inside those tags so I could simply ignore it, but I get an exception of unbound prefix not inside the content handler but in the parser itself; this means that if the exception occurs the entire parsing process is interrupted.



Is there a way of using the sax parser ignoring this kind of error (or namespaces at all)?



p.s. I want to avoid loading all the file in memory as a string and strip namespaces out of it, or having to rewrite the file.


Answer



I found the solution in another thread.




Instead of using Xml.parse you need to manually instantiate a sax parser through the SAXParserFactory and get a reader.



You can then set the reader features.



Among the available features, one disables namespaces and that does the trick.



Reference -> LINK


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...