1. ホーム
  2. java

[解決済み] StreamException: 無効な XML 文字 (Unicode: 0x1a)

2022-02-09 07:32:50

質問

XStreamを使って、ユーザーのオブジェクトをファイルに保存しています。

private void store() {
    XStream xStream = new XStream(new DomDriver("UTF-8"));
    xStream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);

    xStream.alias("configuration", Configuration.class);
    xStream.alias("user", User.class);

    synchronized (ConfigurationDAOImpl.class) {
        try {
            xStream.toXML(configuration, new FileOutputStream(filename.getFile()));
        } catch (IOException e) {
            throw new RuntimeException("Failed to write to " + filename, e);
        }
    }
}

次のコードで読み込もうとすると、Exception: com.thoughtworks.xstream.io.StreamException: が発生します。ドキュメントの要素コンテンツに無効な XML 文字 (Unicode: 0x1a) が見つかりました。

private void lazyLoad() {
    synchronized (ConfigurationDAOImpl.class) {
        // Has the configuration been loaded
        if (configuration == null) {
            if (filename.exists()) {
                try {
                    XStream xStream = new XStream(new DomDriver("UTF-8"));
                    xStream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);

                    xStream.alias("configuration", Configuration.class);
                    xStream.alias("user", User.class);

                    configuration = (Configuration) xStream
                            .fromXML(filename.getInputStream());

                    LOGGER.debug("Loaded configuration from {}.", filename);
                } catch (Exception e) {
                    LOGGER.error("Failed to load configuration.", e);
                }
            } else {
                LOGGER.debug("{} does not exist.", filename);
                LOGGER.debug("Creating blank configuration.");

                configuration = new Configuration();
                configuration.setUsers(new ArrayList<User>());

                // and store it
                store();
            }
        }
    }
}

何か思い当たることは?

解決方法は?

以下の方法で、0x1aをダッシュ文字('-')に置き換えました。

/**
 * This method ensures that the output String has only
 * @param in the string that has a non valid character.
 * @return the string that is stripped of the non-valid character
 */
private String stripNonValidXMLCharacters(String in) {      
    if (in == null || ("".equals(in))) return null;
    StringBuffer out = new StringBuffer(in);
    for (int i = 0; i < out.length(); i++) {
        if(out.charAt(i) == 0x1a) {
            out.setCharAt(i, '-');
        }
    }
    return out.toString();
}