웹 개발
XML에서 한글 읽어들이기.
팩트폭력배
2011. 12. 7. 14:44
InputSource is = new InputSource(new InputStreamReader(new FileInputStream("test.xml"), "UTF-8"));
이렇게 하지 않으면 Element를 통해 읽어 들일때 end tag를 인식하지 못해 에러난다.
대략적 전체 코드.
try {
User user = null;
InputSource is = new InputSource(new InputStreamReader(new FileInputStream(file), "UTF-8"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
if(file != null){
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("client");
user = new User();
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
fstNmElmntLst = fstElmnt.getElementsByTagName("name");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
user.setUserName(((Node) fstNm.item(0)).getNodeValue());
fstNmElmntLst = fstElmnt.getElementsByTagName("id");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
user.setUserId(((Node) fstNm.item(0)).getNodeValue());
fstNmElmntLst = fstElmnt.getElementsByTagName("pass");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
String pw = CipherFactory.getCipher().hashWithKey(user.getUserId(), ((Node) fstNm.item(0)).getNodeValue());
user.setUserPw(pw);
fstNmElmntLst = fstElmnt.getElementsByTagName("category");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
user.setCategoryNo(((Node) fstNm.item(0)).getNodeValue());
fstNmElmntLst = fstElmnt.getElementsByTagName("role");
fstNmElmnt = (Element) fstNmElmntLst.item(0);
fstNm = fstNmElmnt.getChildNodes();
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
logger.error(e);
} catch (SAXException e) {
e.printStackTrace();
logger.error(e);
} catch (IOException e) {
e.printStackTrace();
logger.error(e);
} catch (InvalidKeyException e) {
e.printStackTrace();
logger.error(e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
logger.error(e);
}