微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-从资源加载和解析xml时出现问题

我已经编写了一个解析器,用于从HttpURLConnection解析XML文件.这很好.

问题:我需要重写此文件,以便从本地资源而不是从Internet加载xml文件,但是我无法使它正常工作…只是让您了解原始Web解析器的外观:

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......

现在,这里是我用来尝试从位于资源文件夹中xml / myfile.xml的本地资源解析的代码

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......

本地xml文件和Web文件完全相同…如果有人看一下:http://agens.no/Eniro/Android/SEWheel/Category2.plist.xml

这是堆栈跟踪:
02-01 16:08:45.546:WARN / System.err(19703):org.xml.sax.SAXParseException:预期名称(java.io.InputStreamReader@47668728中的位置START_TAG @ 1:309)

非常感谢您的帮助:)

解决方法:

找到了答案.当文件是res / xml文件夹时,inputstream显示了很多无效字符.当我将它放在res / raw文件夹中时,它工作正常.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。