StreamException: 无效的 XML 字符 (Unicode: 0x1a) [英] StreamException: An invalid XML character (Unicode: 0x1a)
本文介绍了StreamException: 无效的 XML 字符 (Unicode: 0x1a)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 XStream 将用户的对象保存在文件中.
I am using XStream to save the object of user in a file.
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).
When I am trying to read it by the following code I get an Exception: com.thoughtworks.xstream.io.StreamException: : An invalid XML character (Unicode: 0x1a) was found in the element content of the document.
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 替换为破折号 ('-'):
I replaced 0x1a with a dash character ('-') by the following method:
/**
* 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();
}
这篇关于StreamException: 无效的 XML 字符 (Unicode: 0x1a)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文