1

I create a SOAP call, as answer I get a XML string like:

<?xml version="1.0" encoding="utf-8"?>
<sopenevelop>
     <soapbody>
         <ActualAnswer> I want to get whatever is in here </ActualAnswer>
     </soapbody>
</sopenevelop>

So how do I read out the "ActualAnswer" from that xml in android?

I found for example this: XML String parsing in Android? but it did not really say how to filter out an answer.. and couldn't get it working..

in C# I could do this, where xmlanswer is the xml on top, but can't figure it in android

XmlDocument xml = new XmlDocument();
xml.LoadXml (xmlanswer);
string loginanswer =  (xml.GetElementsByTagName ("ActualAnswer") [0].InnerText);
2

4 Answers 4

1

In the past, I've created a nice class to load and handle XML content.

Usage for loading from the resources folder :

val rootTag=XmlTag.getXmlRootTagOfXmlFileResourceId(context,xmlResId)

or, if you have it in a String instance :

val rootTag=XmlTag.getXmlFromString(xmlString)

here's the code:

import android.content.Context
import androidx.annotation.RawRes
import androidx.annotation.XmlRes
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * an xml tag , includes its name, value and attributes
 * @param tagName the name of the xml tag . for example : <a>b</a> . the name of the tag is "a"
 */
class XmlTag(val tagName: String) {
    /** a hashmap of all of the tag attributes. example: <a c="d" e="f">b</a> . attributes: {{"c"="d"},{"e"="f"}}     */
    @JvmField
    var tagAttributes: HashMap<String, String>? = null

    /**list of inner text and xml tags*/
    @JvmField
    var innerTagsAndContent: ArrayList<Any>? = null

    companion object {
        @JvmStatic
        fun getXmlFromString(input: String): XmlTag? {
            val factory = XmlPullParserFactory.newInstance()
            factory.isNamespaceAware = true
            val xpp = factory.newPullParser()
            xpp.setInput(StringReader(input))
            return getXmlRootTagOfXmlPullParser(xpp)
        }

        @JvmStatic
        fun getXmlRootTagOfXmlPullParser(xmlParser: XmlPullParser): XmlTag? {
            var currentTag: XmlTag? = null
            var rootTag: XmlTag? = null
            val tagsStack = Stack<XmlTag>()
            xmlParser.next()
            var eventType = xmlParser.eventType
            var doneParsing = false
            while (eventType != XmlPullParser.END_DOCUMENT && !doneParsing) {
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        val xmlTagName = xmlParser.name
                        currentTag = XmlTag(xmlTagName)
                        if (tagsStack.isEmpty())
                            rootTag = currentTag
                        tagsStack.push(currentTag)
                        val numberOfAttributes = xmlParser.attributeCount
                        if (numberOfAttributes > 0) {
                            val attributes = HashMap<String, String>(numberOfAttributes)
                            val namespacesCount = xmlParser.getNamespaceCount(xmlParser.depth)
                            val nameSpaceToNameSpacePrefixMap = HashMap<String, String>(namespacesCount)
                            for (i in 0 until namespacesCount) {
                                val prefix: String = xmlParser.getNamespacePrefix(i)
                                val ns: String = xmlParser.getNamespaceUri(i)
                                nameSpaceToNameSpacePrefixMap[ns] = prefix
                            }
                            for (i in 0 until numberOfAttributes) {
                                val attrName = xmlParser.getAttributeName(i)
                                val attrValue = xmlParser.getAttributeValue(i)
                                xmlParser.getNamespaceCount(1)
                                val attributeNamespace: String? = xmlParser.getAttributeNamespace(i)
                                if (attributeNamespace.isNullOrEmpty())
                                    attributes[attrName] = attrValue
                                else {
                                    val prefix = nameSpaceToNameSpacePrefixMap[attributeNamespace]
                                            ?: attributeNamespace
                                    attributes["$prefix:$attrName"] = attrValue
                                }
                            }
                            currentTag.tagAttributes = attributes
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        currentTag = tagsStack.pop()
                        if (!tagsStack.isEmpty()) {
                            val parentTag = tagsStack.peek()
                            parentTag.addInnerXmlTag(currentTag)
                            currentTag = parentTag
                        } else
                            doneParsing = true
                    }
                    XmlPullParser.TEXT -> {
                        val innerText = xmlParser.text
                        currentTag?.addInnerText(innerText)
                    }
                }
                eventType = xmlParser.next()
            }
            return rootTag
        }

        /**returns the root xml tag of the given xml resourceId , or null if not succeeded . */
        fun getXmlRootTagOfXmlFileResourceId(context: Context, @XmlRes xmlFileResourceId: Int): XmlTag? {
            val res = context.resources
            val xmlParser = res.getXml(xmlFileResourceId)
            return getXmlRootTagOfXmlPullParser(xmlParser)
        }

        fun getXmlRootTagFromRawResourceId(context: Context, @RawRes xmlFileResourceId: Int): XmlTag? {
            context.resources.openRawResource(xmlFileResourceId).use {
                val factory = XmlPullParserFactory.newInstance()
                factory.isNamespaceAware = true
                val xpp = factory.newPullParser()
                xpp.setInput(it, "utf8")
                return getXmlRootTagOfXmlPullParser(xpp)
            }
        }
    }

    fun addInnerXmlTag(tag: XmlTag) {
        if (innerTagsAndContent == null)
            innerTagsAndContent = ArrayList()
        innerTagsAndContent!!.add(tag)
    }

    fun addInnerText(str: String) {
        if (innerTagsAndContent == null)
            innerTagsAndContent = ArrayList()
        innerTagsAndContent!!.add(str)
    }

    /**formats the xmlTag back to its string format,including its inner tags     */
    override fun toString(): String {
        val sb = StringBuilder()
        sb.append("<").append(tagName)
        val numberOfAttributes = if (tagAttributes != null) tagAttributes!!.size else 0
        if (numberOfAttributes != 0)
            for ((key, value) in tagAttributes!!)
                sb.append(" ").append(key).append("=\"").append(value).append("\"")
        val numberOfInnerContent =
                if (innerTagsAndContent != null) innerTagsAndContent!!.size else 0
        if (numberOfInnerContent == 0)
            sb.append("/>")
        else {
            sb.append(">")
            for (innerItem in innerTagsAndContent!!)
                sb.append(innerItem.toString())
            sb.append("</").append(tagName).append(">")
        }
        return sb.toString()
    }

}

Sign up to request clarification or add additional context in comments.

Comments

0

Use jDom if you want to...

http://www.mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/

PS: doesnt work on linux...

Comments

0
SoapEnvelope result = (SoapEnvelope) envelope.getResponse();
Log.d("result : ", "" + result.toString());
String property_name= result.getProperty("ActualAnswer").toString();

or You can get it by index like as follow:

String property_name= result.getProperty(0).toString();

1 Comment

But "SoapEnvelope" is not known by eclipse.. it tells me to create a new class
0

Try this by DOM

public static String checkLoginStatus(String response)
        throws ParserConfigurationException, SAXException, IOException {
    String status = "";
    DocumentBuilder db = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder();
    InputSource is = new InputSource();
    Document doc = null;

    is.setCharacterStream(new StringReader(response));

    try {
        doc = db.parse(is);
    } catch (SAXException e) {
        Log.d("Wrong XML file structure: ", e.getMessage());
        e.printStackTrace();
        throw e;

    } catch (IOException e) {
        Log.d("I/O exeption: ", e.getMessage());
        e.printStackTrace();
        throw e;
    }

    Node rootNode = doc.getElementsByTagName("soapbody").item(0);
    Element rootElement = (Element) rootNode;
    String status = getTagValue("ActualAnswer", rootElement);
    Log.d("StatusCode", status);
    return status;
}

public static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
            .getChildNodes();
    Node nValue = (Node) nlList.item(0);
    if (nValue == null) {
        return "";
    } else {
        return nValue.getNodeValue();
    }
}

3 Comments

And what about the function "getTagValue" ?
@Onno got the solution or not
it's working like a gem for me .there will be some other issue post your more code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.