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);
4

4 回答 4

1

过去,我创建了一个很好的类来加载和处理 XML 内容。

从资源文件夹加载的用法:

val rootTag=XmlTag.getXmlRootTagOfXmlFileResourceId(context,xmlResId)

或者,如果您在 String 实例中有它:

val rootTag=XmlTag.getXmlFromString(xmlString)

这是代码:

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()
    }

}

于 2013-10-01T11:30:48.910 回答
0

如果你想使用 jDom...

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

PS:不能在linux上运行...

于 2013-10-01T10:43:03.637 回答
0
SoapEnvelope result = (SoapEnvelope) envelope.getResponse();
Log.d("result : ", "" + result.toString());
String property_name= result.getProperty("ActualAnswer").toString();

或者您可以通过索引获取它,如下所示:

String property_name= result.getProperty(0).toString();
于 2013-10-01T10:43:18.883 回答
0

通过 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();
    }
}
于 2013-10-01T10:46:34.217 回答