小编典典

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

java

我已经编写了一个解析器,用于解析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文件和网络文件完全相同…如果有人看的话: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@476687中的START_TAG
@ 1:309)

非常感谢您的帮助:)


阅读 205

收藏
2020-11-30

共1个答案

小编典典

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

2020-11-30