마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

xml 파싱 질문드립니다. 선언이 안되서 호출이안됩니다ㅏ.

0 추천
public class Real extends ActionBarActivity {

 private static final String TAG ="ip";
    String input01;
    TextView txtMsg;
   
    public static String defaultUrl ="http://cpa.gaiacpa.com/ipreturn.php";
 
    Handler handler = new Handler();
   
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actreal);
        input01 ="http://cpa.gaiacpa.com/ipreturn.php";
        txtMsg = (TextView) findViewById(R.id.txtMsg);
 
        // 버튼 이벤트 처리
        Button requestBtn = (Button) findViewById(R.id.requestBtn);
        requestBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String urlStr = input01.toString();
                 
                ConnectThread thread = new ConnectThread(urlStr);
                thread.start();
                 
            }
        });
 
    }
 
    class ConnectThread extends Thread {
     
        String urlStr;

        public ConnectThread(String inStr) {
            urlStr = inStr;
        }
         
        public void run() {
 
            try {
                final String output = request(urlStr);
                handler.post(new Runnable() {
                    public void run() {
                        txtMsg.setText(output);
                    }
                });
                 
            } catch(Exception ex) {
                ex.printStackTrace();
            }
 
        }
         
 
        private String request(String urlStr) {
            StringBuilder output = new StringBuilder();
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(urlStr);
 
                List<NameValuePair> fields = new ArrayList<NameValuePair>(1);
                fields.add(new BasicNameValuePair("data", "test"));
                httppost.setEntity(new UrlEncodedFormEntity(fields));
 
                Log.d("SampleHTTPClient", "\nRequest using HttpClient ...");
                HttpResponse response = client.execute(httppost);
                Log.d("SampleHTTPClient", "\nResponse from HttpClient ...");
 
                InputStream instream = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(instream)) ;
                String line = null;
              
               
                while(true) {
                    line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    output.append(line + "\n");
                }
                 
                reader.close();
            } catch(Exception ex) {
                Log.e("SampleHTTPClient", "Exception in processing response.", ex);
            }
 
            return output.toString();
        }
       
    }


현재 코드는url을 불러와서 버튼을 누르면 화면에 뿌려주는 형식입니다.

URL을 이용해서 파서로 한가지의 태그만 집어오려고합니다. ( 현재 네이버 url은 교체한 url이에요)


그런데 파서가 쓰면 자꾸 변수에서 에러가 나서 진행이 되지않습니다...

<ip> 태그만 끄집어 내려고하는데... 어떻게 수정해야 할지 모르겠네요ㅠ

추가하면 안돌아가고 계쏙 제자리 걸음이네요ㅠ

 

음냥꾸닌인강 (340 포인트) 님이 2014년 7월 24일 질문

2개의 답변

0 추천
String getIp(String xml) {
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();  
  DocumentBuilder builder = builderFactory.newDocumentBuilder();  
  XPath xpath = XPathFactory.newInstance().newXPath();  
    
  Document document = builder.parse(new InputSource(new StringReader(xml)));
    
  expression = "/root/ip/text()";
  return xpath.evaluate(expression, document, XPathConstants.STRING).toString();
}
aucd29 (218,390 포인트) 님이 2014년 7월 24일 답변
Document document = builder.parse(new InputSource(new StringReader(xml)));

Description    Resource    Path    Location    Type
Type mismatch: cannot convert from Document to DocumentsContract.Document    Real.java 라고 뜹니다.

                
              expression = "/root/ip/text()";
              return xpath.evaluate(expression, document, XPathConstants.STRING).toString();

inputSource에서 자꾸 에러가 나는데 잡을수가없네요..ㅠ
서버에서 xml 을 받아다가 xml string 을 대입시킨거 맞나요??
이런식으로 해서 동작되나 보세요

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><ip>210.216.54.2</ip></root>";
Document document = builder.parse(new InputSource(new StringReader(xml)));
직접 넣어주는 식으로 가장 먼저 바꾸어 시도해봣엇는데ㅠ
이방법도 똑같은 에러가 나더라구요ㅠ
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><ip>210.216.54.2</ip></root>";
            String res = getIp(xml);
            Log.d(TAG, res);
        } catch (Exception e) {
            Log.e(TAG, "onCreate", e);
        }
    }

    String getIp(String xml) throws Exception {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        XPath xpath = XPathFactory.newInstance().newXPath();

        Document document = builder.parse(new InputSource(new StringReader(xml)));
        String expression = "/root/ip/text()";

        return xpath.evaluate(expression, document, XPathConstants.STRING).toString();
    }

테스트 해보니 잘 됩니다. document  다른걸 import 한것 같네요?
그리고 이 정도 정보를 드려도 해결못하면
심각한겁니다.

코딩 할 생각 하지 마시고 일단 관련 공부 부터 먼저 하세요
넵 문제는 해결햇지만 공부부터 하고 다시 오겠습니다.
0 추천
사용자의 IP를 알아내기 위해 매우 노력하고 계십니다만,

이 방법은 사용자 기기가 wifi로 공유기에  연결된 경우 공유기 ip만 알 수 있습니다.
익명사용자 님이 2014년 7월 24일 답변
그건 괜찮습니다. 답변감사합니다.
...