Code example for XmlPullParser

Methods: defineEntityReplacementText, setInput

0
 
    public void testManuallyRegisteredEntitiesWithDoctypeParsing() throws Exception { 
        String xml = "<foo>&a;</foo>";
        XmlPullParser parser = newPullParser(xml);
        try { 
            parser.defineEntityReplacementText("a", "android");
            fail();
        } catch (UnsupportedOperationException expected) {
        } catch (IllegalStateException expected) {
        } 
    } 
 
    public void testDoctypeWithNextToken() throws Exception { 
        String xml = "<!DOCTYPE foo [<!ENTITY bb \"bar baz\">]><foo>a&bb;c</foo>";
        XmlPullParser parser = newPullParser(xml);
        assertEquals(XmlPullParser.DOCDECL, parser.nextToken());
        assertEquals(" foo [<!ENTITY bb \"bar baz\">]", parser.getText());
        assertNull(parser.getName());
        assertEquals(XmlPullParser.START_TAG, parser.nextToken());
        assertEquals(XmlPullParser.TEXT, parser.next());
        assertEquals("abar bazc", parser.getText());
        assertEquals(XmlPullParser.END_TAG, parser.next());
        assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
    } 
 
    public void testDoctypeSpansBuffers() throws Exception { 
        char[] doctypeChars = new char[READ_BUFFER_SIZE + 1];
        Arrays.fill(doctypeChars, 'x');
        String doctypeBody = " foo [<!--" + new String(doctypeChars) + "-->]";
        String xml = "<!DOCTYPE" + doctypeBody + "><foo/>";
        XmlPullParser parser = newPullParser(xml);
        assertEquals(XmlPullParser.DOCDECL, parser.nextToken());
        assertEquals(doctypeBody, parser.getText());
        assertEquals(XmlPullParser.START_TAG, parser.next());
        assertEquals(XmlPullParser.END_TAG, parser.next());
        assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
    } 
 
    public void testDoctypeInDocumentElement() throws Exception { 
        assertParseFailure("<foo><!DOCTYPE foo></foo>"); 
    } 
 
    public void testDoctypeAfterDocumentElement() throws Exception { 
        assertParseFailure("<foo/><!DOCTYPE foo>"); 
    } 
 
    private void assertParseFailure(String xml) throws Exception {
        XmlPullParser parser = newPullParser();
        parser.setInput(new StringReader(xml));
        try { 
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
            } 
            fail();
        } catch (XmlPullParserException expected) {
        } 
    } 
 
    private String repeat(char c, int length) {
        char[] chars = new char[length];
        Arrays.fill(chars, c);
        return new String(chars);
    } 
 
    private XmlPullParser newPullParser(String xml) throws XmlPullParserException {
        XmlPullParser result = newPullParser();
        result.setInput(new StringReader(xml));
        return result;
    } 
 
    /** 
     * Creates a new pull parser.