从字符串中的 XML 获取数据 - Android

Get data from XML in String - Android

我正在使用 SOAP 服务获取票证。我发送用户并通过,我在字符串中得到 xml。为此,我正在使用 ksoap2。

@Override
protected String doInBackground(String... params) {

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty(USER, params[0]);
    request.addProperty(PASS, params[1]);

    SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapEnvelope.bodyOut = request;
    soapEnvelope.setOutputSoapObject(request);

    HttpTransportSE HttpTransport = new HttpTransportSE(URL);
    try {
        HttpTransport.call(SOAP_ACTION, soapEnvelope);
        return soapEnvelope.getResponse().toString();
    } catch (IOException | XmlPullParserException e) {
        e.printStackTrace();
        return null;
    }
}

@Override
    protected void onPostExecute(String XML) {
        super.onPostExecute(XML);
        if (result != null) {
           // Here I need to get data from XML

        }
    }

我的 XML 字符串如下所示:

<?xml version="1.0" encoding="UTF-8" ?>
<resp err="0">
<ticket>1234567989</ticket>
</resp>

所以我需要获取错误编号和票号。

不要将您的响应转换为字符串 return ,而是使用 getProperty() 方法获取您需要的属性并将它们转换为字符串。我是这样做的:

    String ticket;

    public void getSoap() {

    SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.implicitTypes = false;
    envelope.setOutputSoapObject(request);
    HttpTransportSE httpTransportSe = new HttpTransportSE(URL);
    httpTransportSe.debug = true;
    SoapObject response = null;

    try {
        httpTransportSe.call(SOAPACTION, envelope);
        response = (SoapObject) envelope.getResponse();
        ticket = response.getProperty("ticket").toString();

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

}

从属性中获取 "err" 元素可能需要更多研究,但您可以在获取 ticket:

的地方尝试此操作
String err = response.getAttribute("err").toString;

希望这对您有所帮助,祝您编码愉快!

使用JDom解析XML:

String xmlString = //get xml string;  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try  
{  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse( new InputSource( new StringReader( xmlString ) ) );  
} catch (Exception e) {  
    e.printStackTrace();  
}

接下来通过 XPath 从文档 http://www.w3schools.com/xpath/xpath_examples.asp

中获取值