2011-12-14 427 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字符(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(); 
      } 
     } 
    } 
} 

任何想法?

+0

可能相關:http://stackoverflow.com/a/8427929/486504 – 2011-12-14 14:38:08

回答

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

0x1a是無效的xml字符。沒有辦法在xml 1.0文檔中表示它。

在以下範圍內從http://en.wikipedia.org/wiki/XML#Valid_characters

Unicode碼位在XML有效1.0 文件:[9] U + 0009,U + 000A,U + 000D:這些是唯一C0控制 在XML 1.0中接受; U + 0020-U + D7FF,U + E000-U + FFFD:這不包括BMP中的一些 (並非全部)非字符(所有代理,U + FFFE和U + FFFF 都是禁止的)。 U + 10000-U + 10FFFF:這包括 補充飛機中的所有代碼點,包括非字符。

+0

謝謝你的答案。我用一個方法用一個破折號字符(' - ')替換了0x1a。 – 2011-12-15 13:20:28

+0

如果這是正確的答案,你可以做一個upvote/accept – jontro 2011-12-15 23:30:38