如何将符合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 (ParserConfigurationException 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. xml
[解决办法]
这样,首先确定你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的对象。
Document document = sr.read(is);
Element root = document.getRootElement();
List<?> elementlist = root.elements("city");
for (Object obj : elementlist) {
Element row = (Element) obj;
String quName = row.attribute("quName").getText();
String pyName = row.attribute("pyName").getText();
proMap.put(quName, pyName);
}
/**
* 把输入流转化成UTF-8格式的输入流
* @param in
* @param charset
* @return
* @throws Exception
*/
public static InputStream fromInputStreamToInputStreamInCharset(
InputStream in, String charset) throws Exception {
StringBuilder builder=new StringBuilder();
byte[] buffer = new byte[2048];
int len = -1;
while ((len = in.read(buffer)) != -1) {
builder.append(EncodingUtils.getString(buffer, 0, len, "UTF-8"));
}
return IOHelper.fromStringToIputStream(builder.toString());
}
DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document=db.parse(new InputSource(new StringReader(你的xml字符串)));