Java/Android xml解析导致NullPointerException
我在 Android 上解析 XML 文件时遇到问题。
我的 example.xml 文件如下所示:
<categories>
<example>something</example>
</categories>
我的 Java 代码:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getResources().openRawResource(R.xml.examples));
doc.getDocumentElement().normalize(); //here it throws NullPointerException
当我尝试标准化()时,它抛出 NullPointerException。
我受到这个简单教程的启发 http://sanjaal.com/java/tag/getdocumentelementnormalize/
谁能告诉我我做错了什么?谢谢
I have a problem with parsing XML file on android.
My examples.xml file look like this:
<categories>
<example>something</example>
</categories>
And my Java code:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getResources().openRawResource(R.xml.examples));
doc.getDocumentElement().normalize(); //here it throws NullPointerException
It throws a NullPointerException when I try to normalize().
I am inspired by this simple tutorial http://sanjaal.com/java/tag/getdocumentelementnormalize/
Can anyone tell me what I'm doing wrong? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将您的 xml 文件移至
res/raw
文件夹,然后尝试以下操作:让我知道这是否有效。
编辑:如果您查看 http://developer .android.com/reference/android/content/res/Resources.html#openRawResource%28int%29 它基本上说你只能在可绘制、声音和原始资源上使用它。
Try moving your xml file to the
res/raw
folder, then try this:Let me know if that works.
EDIT: if you look at http://developer.android.com/reference/android/content/res/Resources.html#openRawResource%28int%29 it basically says you can only use that on drawable, sound and raw resources.
尝试 XmlPullParser。我认为这更容易一些。
XmlPullParser | Android 开发者
Try XmlPullParser. It's a little bit easier, I think.
XmlPullParser | Android Developers
尝试 Project|Clean - 它可能无法从您的资源中获取原始 XML。 Eclipse 看起来有点不稳定,我有时会更改代码&在清理之前它不会接受更改。
Try Project|Clean - it might not be getting the raw XML from your resources. Eclipse seems a bit flaky that way, I sometimes change code & it doesn't pick up the changes until its cleaned.