Reputation: 7204
I've been fighting trying to parse a basic xml file in a little test android app.
The code I have is the following:
InputStream is = getResources().openRawResource(R.xml.content);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is,"UTF-8"); //Blows up right here.
// Bunch more stuff here
}
My xml looks like the following:
<?xml version="1.0" ?>
<main>
<background>
<defintion>This is a test</defintion>
</background>
</main>
The problem is that when I try to parse this I get an org.xml.sax.SAXParseException: Unexpected token (position:TEXT unprintable characters here ...@3:252 in java.io.InputStreamReader@411f3898)
error.
I googled around and all the other solutions I found don't seem to work.
I double checked that the file is UTF-8, and changed it's encoding back and forth between UTF-16 and UTF-8 (tried both with and without BOM) with notepad++, and updated the program to properly reflect this, but no matter what I do, I always get this error. I'm sure I must just be missing something very obvious, but no matter what series of combinations I try this always fails.
Upvotes: 2
Views: 1379
Reputation: 9128
I've encountered the same problem as yours. I finally found the solution:
Never put your xml in res/xml. The xml file will be encoded by android sdk, thus can't be read correctly. However, when you put it in res/raw, the xml file exported to the app will be intact.
Upvotes: 1
Reputation: 132972
First put your content.xml file in res/raw folder then parse it as:
Your xml file res/raw/content.xml :
<?xml version="1.0" encoding="utf-8"?>
<main>
<background>
<defintion>This is a test</defintion>
</background>
</main>
and parse it as:
InputStream is = getResources().openRawResource(R.raw.content);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
try {
Document doc = dBuilder.parse(is,"UTF-8");
NodeList nl = doc.getElementsByTagName("main");
System.out.println("NodeList NodeList"+nl.getLength());
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //Blows up right here.
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 1