2011-12-14 35 views
2

XStreamを使用して、ユーザーのオブジェクトをファイルに保存しています。StreamException:無効なXML文字(Unicode:0x1a)

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); 
     } 
    } 
} 

私は次のコードでそれを読みしようとしている私は例外を取得:com.thoughtworks.xstream.io.StreamException:無効なXML文字(ユニコード: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(); 
      } 
     } 
    } 
} 

+0

おそらく関連:http://stackoverflow.com/a/8427929/486504 –

答えて

4

私はダッシュ文字で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(); 
} 
+8

あなたは正しい答えとしてjontrosの回答を受け入れるべきでした。彼はあなたの質問に答えて、良い説明をしました。 – SamStephens

+0

他の回答を真剣に受け入れてください。何人かの司会者がここに怒られるでしょう。 – Lupocci

+1

あなた自身のことではなく、Jontroの答えを受け入れるべきだったからです。 –

22

0x1aは無効なxml文字です。それをxml 1.0文書で表現する方法はありません。 [9] U + 0009、U + 000A、U + 000D:以下の範囲でhttp://en.wikipedia.org/wiki/XML#Valid_characters

Unicodeコードポイントから引用

は、XML 1.0 文書に有効なこれらのみC0が を制御していますXML 1.0で受け入れられました。 U + 0020-U + D7FF、U + E000-U + FFFD:これは、BMP内の一部の文字(すべてではない)を除外します(すべてのサロゲート、U + FFFEおよびU + FFFF は禁止されています)。 U + 10000-U + 10FFFF:非文字を含む 補助面のすべてのコードポイントが含まれます。

+0

をいただき、ありがとうございます答え。私は方法で0x1aをダッシュ​​文字( ' - ')に置き換えました。 –

+0

あなたは正しい答えがあればupvote/acceptをすることができます – jontro