Open XML file from res/xml in Android

后端 未结 3 1432
暖寄归人
暖寄归人 2020-12-09 22:16

I created a Java application which opens an xml file that looks something like this:


  

        
相关标签:
3条回答
  • 2020-12-09 22:54

    Try this,

    this.getResources().getString(R.xml.test); // returns you the path , in string,invoked on activity object
    
    0 讨论(0)
  • 2020-12-09 22:56

    I tried the approach using openRawResource and got a SAXParseException. So, instead, I used getXml to get a XmlPullParser. Then I used next() to step through the parsing events. The actual file is res/xml/dinosaurs.xml.

    XmlResourceParser parser = context.getResources().getXml(R.xml.dinosaurs);
    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        switch (eventType) {
            case XmlPullParser.START_DOCUMENT :
                Log.v(log_tag, "Start document");
                break;
            case XmlPullParser.START_TAG :
                Log.v(log_tag, "Start tag " + parser.getName() );
                break;
            case XmlPullParser.END_TAG :
                Log.v(log_tag, "End tag " + parser.getName() );
                break;
            case XmlPullParser.TEXT :
                Log.v(log_tag, "Text " + parser.getText() );
                break;
            default :
                Log.e(log_tag, "Unexpected eventType = " + eventType );
        }
        eventType = parser.next();
    }
    
    0 讨论(0)
  • 2020-12-09 22:57

    If it's in the resource tree, it'll get an ID assigned to it, so you can open a stream to it with the openRawResource function:

    InputStream is = context.getResources().openRawResource(R.xml.data);

    As for working with XML in Android, this link on ibm.com is incredibly thorough.

    See Listing 9. DOM-based implementation of feed parser in that link.

    Once you have the input stream (above) you can pass it to an instance of DocumentBuilder:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(this.getInputStream());
    Element root = dom.getDocumentElement();
    NodeList items = root.getElementsByTagName("TheTagYouWant");
    

    Keep in mind, I haven't done this personally -- I'm assuming the code provided by IBM works.

    0 讨论(0)
提交回复
热议问题