如何将符合XML的字符串转换层XML的 document对象
DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
Document doc = null;
try {
builder = factory.newDocumentBuilder();
try {
doc = builder.parse(new ByteArrayInputStream(str.getBytes()));
} catch (
SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (
IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Parser
ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence.
------解决方案--------------------这样,首先确定你str字符串打印出来不会乱码,
然后把这个字符串转化成Inputstream流。然后用SAXreader读就可以了。
字符串转化成io流:
public static InputStream fromStringToIputStream(String s) {
if (s != null && !s.equals("")) {
try {
ByteArrayInputStream stringInputStream = new ByteArrayInputStream(
s.getBytes());
return stringInputStream;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
InputStream is = IOHelper.fromInputStreamToInputStreamInCharset(in,"utf-8");//我这个方法是把is流转化成utf-8格式的,你愿意使用的话可以参考下,在下面。
SAXReader sr = new SAXReader();// 获取读取xml的对象。