SAXParser解析数据的问题

时间:2010-10-06 10:28:21

标签: java saxparser

<message priority="info">PARAMETRI:</message>
<message priority="info">vrednost: 2.0</message>
<message priority="info">rank: 0.75</message>
−
<message priority="info">
objekt: irc.kis.model.pomozniRazredi.CasovniInterval.CasovniInterval(Date, Date)
</message>
<message priority="info">iid_tipa: 3</message>
<message priority="info">iid_metrike: 14</message>
<message priority="info">iid_izracuna: 140</message>
<message priority="info">done in 205776 ms</message>
<message priority="info">---------</message>
<message priority="info">Indeksi kakovosti</message>
<message priority="info">QI01: 3.9249</message>
<message priority="info">QI02: 4.0335</message>
<message priority="info">QI03: 4.0966</message>
<message priority="info">QI04: 4.3823</message>
<message priority="info">---------</message>
<message priority="info">QI05: 3.9401</message>
<message priority="info">QI06: 4.2479</message>
<message priority="info">QI07: 4.4984</message>
<message priority="info">QI08: 4.3534</message>
<message priority="info">QI09: 3.8455</message>
<message priority="info">QI10: 4.0195</message>
<message priority="info">QI11: 4.6222</message>

这是我的xml日志。我可以用java SAXParser出来吗

Indeksi kakovosti
QI01: 3.9249
QI02: 4.0335
QI03: 4.0966
QI04: 4.3823

----

之间的任何事情

如果是,如何?

2 个答案:

答案 0 :(得分:1)

是的,你可以这样做(假设你的xml格式正确)。您必须使用计数器实例变量创建ContentHandler,以告知您到目前为止找到了多少---------个分隔符。

不要使用characters()来执行此操作,因为可以多次调用characters()。而是使用characters()缓冲文本读取,使用endElement()读取最终文本并测试和增加计数器。

所以ContentHandler看起来像:

DefaultHandler hander = new DefaultHander() {
    private String marker = "---------";
    private int markerCount = 0;

    private java.io.CharArrayWriter buffer = new java.io.CharArrayWriter();

    public void characters(char ch[], int start, int length) {
        buffer.append(ch, start, length);
    }   

    public void endElement( String namespaceURI, String localName, String qName ) {
        String elementText = buffer.toString();
        if (elementText.startsWith(marker) {
            markerCount += 1;
        }
        else if (markerCount == 1) {
            System.out.println(elementText);
        }
        buffer.reset();
    }
};

答案 1 :(得分:0)

一定是这样的。

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {
        boolean indexes;

        public void characters(char ch[], int start, int length)
                throws SAXException {
            String value = new String(ch, start, length);
            boolean changeState = value.startsWith("---");//change this, as you need
            if (!changeState && indexes){
                System.out.println(new String(ch, start, length));
            }
            if(changeState) indexes = !indexes;
        }

    };
    parser.parse(PATH_TO_FILE, handler);

但是你的文档必须格式良好(带有根元素,没有像第四行那样的未知字符)。