Is there an easier way to parse XML in Java?

前端 未结 13 535
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 02:50

I\'m trying to figure out how to parse some XML (for an Android app), and it seems pretty ridiculous how difficult it is to do in Java. It seems like it requires creating an

13条回答
  •  一个人的身影
    2020-11-30 03:05

    A couple of weeks ago I battered out a small library (a wrapper around javax.xml.stream.XMLEventReader) allowing one to parse XML in a similar fashion to a hand-written recursive descent parser. The source is available on github, and a simple usage example is below. Unfortunately Android doesn't support this API but it is very similar to the XmlPullParser API, which is supported, and porting wouldn't be too time-consuming.

    accept("tilesets");
        while (atTag("tileset")) {
            String filename = attrib("file");
            File tilesetFile = new File(filename);
            if (!tilesetFile.isAbsolute()) {
                tilesetFile = new File(FilenameUtils.concat(file.getParent(), filename));
            }
            int tilesize = Integer.valueOf(attrib("tilesize"));
            Tileset t = new Tileset(tilesetFile, tilesize);
            t.setID(attrib("id"));
            tilesets.add(t);
    
            accept();
            close();
        }
    close();
    
    expect("map");
    
    int width       = Integer.valueOf(attrib("width"));
    int height      = Integer.valueOf(attrib("height"));
    int tilesize    = Integer.valueOf(attrib("tilesize"));
    

提交回复
热议问题