0
            DocumentBuilderFactory f_server = DocumentBuilderFactory.newInstance();
            f_server.setValidating(false);
            DocumentBuilder builder_server = f_server.newDocumentBuilder();
            Document doc_server = builder_server.parse(url);

            String = // строка xml хранящегося в doc_server.
6
  • 1
    doc_server.toString()?
    – Mage
    4 дек 2012 в 10:33
  • 1
    А зачем вообще городить фабрики и билдеры, чтобы потом считать в строку?
    – misha_m
    4 дек 2012 в 10:36
  • тоже вариант, можно просто считать HTTP клиентом
    – Mage
    4 дек 2012 в 10:38
  • doc_server.toString()? // пробовал не работает. возвращает #document: null. Я просто привёл часть кода для наглядности. Вроде бы просто из Document преобразовать в String. 4 дек 2012 в 10:43
  • значит null
    – Gorets
    4 дек 2012 в 10:46

1 ответ 1

1
public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

public Document getDomElement(String xml){
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
                catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
            // return DOM
            return doc;
            }
Просто и наглядно. А потом делайте со своим дом то что нужно :-)
4
  • мне нуна в строку, а не из неё... 4 дек 2012 в 10:58
  • добавил код, смотри 4 дек 2012 в 11:03
  • а какие библиотеки импортировать? 4 дек 2012 в 11:15
  • ctr+shift+o там всё импортнётся само или выберите по логике библиотеки. 4 дек 2012 в 11:23

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.