protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
btnTest = (Button)findViewById(R.id.btnTest);
new Thread() {
public void run() {
try{
StringBuffer sBuffer = new StringBuffer();
String urlAddr ="http://www.forest.go.kr/newkfsweb/kfi/kfs/openapi/gdTrailInfoOpenAPI.do?key=1861e624e1bb40608733d9b7c2adf688";//파싱할 URL 입력
URL url = new URL(urlAddr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if(conn != null){
conn.setConnectTimeout(20000);
conn.setUseCaches(false);
if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
while(true){
String line = br.readLine();
if(line==null){
break;
}
sBuffer.append(line);
}
br.close();
conn.disconnect();
}
}
xml = sBuffer.toString();
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),"접근불가",Toast.LENGTH_LONG).show();
} // xmlData에 xml파일 내용을 담기 위한 호출
}
}.start();
btnTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//tv.setText(xml);
xml.replace("![CDATA[",null).replace("]]",null);
parse();
}
});
}
///// 파싱상에서 문제가 발생하는듯.... 노드를 읽어들이지 못함. Why?
public void parse(){
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes());
Document doc = documentBuilder.parse(is);
Element element = doc.getDocumentElement();
NodeList items = element.getElementsByTagName("mntNm"); //파싱할 노드의 태그네임 입력
int n = items.getLength();
StringBuffer sBuffer = new StringBuffer();
for(int i=0 ; i < n ; i++){
Node item = items.item(i);
Node text = item.getFirstChild();
String itemValue = text.getNodeValue();
str = Integer.toString((int) Double.parseDouble(itemValue));
sBuffer.append(str);
}
tv.append(str);
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),"에러",Toast.LENGTH_LONG).show();
}
}
읽어들이는 Xml파일 중에서
태그 내용이 CDATA로 되어있는 것들이 있어서 처음에 파싱을 하지 못하는 문제때문에
replace를 사용해서 파싱을 진행하려고 하고있습니다.
제가 만들고자 하는 건 버튼을 누를 경우 파싱을 진행해서 mntNm이란 태그의 내용들을 읽어오려고 하고 있는데요
xml.replace.... 이 부분에서 에러가 발생하면서 죽어버립니다.
제가 파싱하는 방법이 잘못된건지 replace를 잘못 선언한건지 모르겠어서 올립니다.