IT/java

java xml 파일 읽기

조원태 2020. 6. 24. 12:28
반응형

아래와 같은 xml 파일을 자바에서 읽기

환경에 관련된 파일은 소스 안에 넣는 것보다 외부파일로 만들어서 관리를 하게 되면 
소스 파일 수정없이 프로그램에 영향을 줄 수 있습니다.

파일명 : sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<Database>
<ip>127.0.0.1</ip>
<port>1521</port>
<serviceid>oracle</serviceid>
<userid>dbID</userid>
<password>dbPassword</password>
</Database>

파일명 MyClassName.java

public void MyClassName(){
String address = "";
String port = "";
String serviceid = "";
String userid = "";
String password = "";

try{

String currDir = MyClassName.class.getResource(".").getPath();
File file = new File(currDir+"/sample.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
document.getDocumentElement()normalize();

NodeList nList = document.getElementsByTagName("Database");

if( nList.getLength() > 0) {
Node nNode = nList.item(0);
if(nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
this.address = getTagValue("address", eElement);
this.port = getTagValue("port", eElement);
this.serviceid= getTagValue("serviceid", eElement);
this.userid= getTagValue("userid", eElement);
this.password= getTagValue("password", eElement);
}

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

private static String getTagValue(String tag, Element eElement){
NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes();

Node nValue = (Node) nlList.item(0);
if( nValue == null ) return null;
return nValue.getNodeValue();
}

}

위 소스를 이용하면 xml을 파싱하여 Element 정보를 가져올 수 있다..

 

반응형

'IT > java' 카테고리의 다른 글

ajax post json 을 jsp request 로 받기  (0) 2020.08.11
java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts  (0) 2020.08.05