java 读取 GBK 编码的XML字串

try {
    
InputStream is = new ByteArrayInputStream(xml.getBytes("GBK"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
Document doc = db.parse(is);

} catch (Exception ex) {
ex.printStackTrace();
}


另一种读取方式:

private static Map getWholeXMLKeyValue(String file) {
Map sqlMap = new HashMap();
try {
Document document = parse(file);
Element root = document.getRootElement();
// 遍歷根節點(sql_config)的所有子節點

for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element element = (Element) iter.next();
// 遍歷sqls節點的的所有子節點

for (Iterator iterInner = element.elementIterator(); iterInner.hasNext();) {
Element elementInner = (Element) iterInner.next();
// 遍歷(domestic...)等節點的的所有子節點,并取得其鍵值對
for (Iterator iterSub = elementInner.elementIterator(); iterSub.hasNext();) {
Element innerSub = (Element) iterSub.next();
sqlMap.put(element.getName() + "." + elementInner.getName() + "." + innerSub.getName(), innerSub.getStringValue());
}
}
}
} catch (DocumentException ex) {
log.error("The resource file(" + file.toString() + ") was not found. ", ex);
}
return sqlMap;
}

private static Document parse(String file) throws DocumentException {
ClassLoader classLoader = null;
SAXReader reader = new SAXReader();
classLoader = Thread.currentThread().getContextClassLoader();
Document document = reader.read(classLoader.getResourceAsStream(file));
return document;
}

你可能感兴趣的:(java,java)