我一直在努力尝试在一个小测试 Android 应用程序中解析基本的 xml 文件。
我的代码如下:
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
}
我的 xml 如下所示:
<?xml version="1.0" ?>
<main>
<background>
<defintion>This is a test</defintion>
</background>
</main>
问题是,当我尝试解析它时,我得到一个 org.xml.sax.SAXParseException: Unexpected token (position:TEXT unprintable characters here ...@3:252 in java.io.InputStreamReader@411f3898)
错误。
我用谷歌搜索了一下,发现所有其他解决方案似乎都不起作用。
我仔细检查了该文件是否为 UTF-8,并使用 notepad++ 在 UTF-16 和 UTF-8 之间来回更改了它的编码(尝试使用和不使用 BOM),并更新程序以正确反射(reflect)这一点,但是无论我做什么,我总是会收到此错误。我确信我一定错过了一些非常明显的东西,但无论我尝试什么系列的组合,这总是会失败。
最佳答案
首先将您的 content.xml 文件放入 res/raw 文件夹中,然后将其解析为:
您的 xml 文件res/raw/content.xml:
<?xml version="1.0" encoding="utf-8"?>
<main>
<background>
<defintion>This is a test</defintion>
</background>
</main>
并将其解析为:
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();
}
关于java - 似乎无法在 android 中解析 xml 文件而不出现 saxparser 意外 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12927278/