代码之家  ›  专栏  ›  技术社区  ›  JR Lawhorne

如何在J2ME中从流中去除无效的XML字符?org.xml.sax.SAXParseException:无效字符

  •  1
  • JR Lawhorne  · 技术社区  · 16 年前

    目前,我得到: org.xml.sax.SAXParseException: Invalid character '' encountered .

    我希望看到一种在输入流上附加无效字符剥离器的快速方法,以便流只通过验证器/剥离器进入解析调用。i、 我试图避免保存流的内容。

    处理者 是对 DefaultHandler
    网址 是包含API的字符串 URL

    hconn = (HttpConnection) Connector.open(url,Connector.READ_WRITE,true);
    
    ...
    
    try{
       XMLParser parser = new XMLParser();
       InputStream input = hconn.openInputStream();
       parser.parse(input, handler);
       input.close();
    } catch (SAXException e) {
       Logger.getInstance().error("getViaHTTP() - SAXException - "+e.toString());
    }
    
    2 回复  |  直到 13 年前
        1
  •  2
  •   Matthew Flaschen    16 年前

    很难在InputStream上附加剥离器,因为流是面向字节的。在一个特定的时间做这件事可能更有意义 Reader

    public class StripReader extends Reader
    {
        private Reader in;
        public StripReader(Reader in)
        {
        this.in = in;
        }
    
        public boolean markSupported()
        {
        return false;
        }
    
        public void mark(int readLimit)
        {
        throw new UnsupportedOperationException("Mark not supported");
        }
    
        public void reset()
        {
        throw new UnsupportedOperationException("Reset not supported");
        }
    
        public int read() throws IOException
        {
        int next;
        do
        {
            next = in.read();
        } while(!(next == -1 || Character.isValidCodePoint(next)));
    
        return next; 
        }
    
        public void close() throws IOException
        {
        in.close();
        }
    
        public int read(char[] cbuf, int off, int len) throws IOException
        {
        int i, next = 0;
        for(i = 0; i < len; i++)
        {
            next = read();
            if(next == -1)
            break;
            cbuf[off + i] = (char)next;
        }
        if(i == 0 && next == -1)
            return -1;
        else
            return i;
        }
    
        public int read(char[] cbuf) throws IOException
        {
        return read(cbuf, 0, cbuf.length);
        }
    }
    

    然后构建一个 InputSource

        2
  •  0
  •   alphazero    16 年前

    使用 FilterInputStream . 推翻 FilterInputStream#read 以过滤有问题的字节。