簡體   English   中英

從流中過濾/刪除無效的xml字符

[英]filter/remove invalid xml characters from stream

首先,我不能更改xml的輸出,它是由第三方生產的。 他們在xml中插入無效字符。 我得到了xml字節流表示形式的InputStream。 除了將流消費為String並對其進行處理之外,他們是否更干凈的方法來過濾出有害字符? 我發現了這一點: 使用FilterReader,但這對我不起作用,因為我有字節流而不是字符流。

為了值得,這是jaxb解組過程的全部內容,以防萬一提供選項。

如果字符流不好,我們不願意拋棄整個流。 我們已決定將其刪除並繼續。

這是我嘗試構建的FilterReader。

public class InvalidXMLCharacterFilterReader extends FilterReader {

    private static final Log LOG = LogFactory
    .getLog(InvalidXMLCharacterFilterReader.class);

    public InvalidXMLCharacterFilterReader(Reader in) {
        super(in);
    }

    public int read() throws IOException {
        char[] buf = new char[1];
        int result = read(buf, 0, 1);
        if (result == -1)
        return -1;
        else
        return (int) buf[0];
    }

    public int read(char[] buf, int from, int len) throws IOException {
        int count = 0;
        while (count == 0) {
            count = in.read(buf, from, len);
            if (count == -1)
                return -1;

            int last = from;
            for (int i = from; i < from + count; i++) {
                LOG.debug("" + (char)buf[i]);
                if(!isBadXMLChar(buf[i])) {
                    buf[last++] = buf[i];
                }
            }

            count = last - from;
        }
        return count;
    }

    private boolean isBadXMLChar(char c) {
        if ((c == 0x9) ||
            (c == 0xA) ||
            (c == 0xD) ||
            ((c >= 0x20) && (c <= 0xD7FF)) ||
            ((c >= 0xE000) && (c <= 0xFFFD)) ||
            ((c >= 0x10000) && (c <= 0x10FFFF))) {
            return false;
        }
        return true;
    }

}

這是我解組的方式:

jaxbContext = JAXBContext.newInstance(MyObj.class);
Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
Reader r = new InvalidXMLCharacterFilterReader(new BufferedReader(new InputStreamReader(is, "UTF-8")));
MyObj obj = (MyObj) unMarshaller.unmarshal(r);

和一些示例錯誤的XML

<?xml version="1.0" encoding="UTF-8" ?>
<foo>
    bar&#x01;
</foo>

為了使用過濾器執行此操作,該過濾器需要了解XML實體,因為(至少在您的示例中,有時甚至在實際使用中)不良字符作為實體存在於xml中。

篩選器將您的實體視為由6個完全可接受的字符組成的序列,因此沒有剝離它們。

破壞JAXB的轉換將在此過程的后面進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM