如何在android(java)中读出XML

时间:2013-10-01 10:39:29

标签: java android xml

我创建了一个SOAP调用,作为答案,我得到了一个XML字符串,如:

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

那么如何从android中的那个xml中读出“ ActualAnswer ”?

我找到了这样的例子: XML String parsing in Android? 但它并没有真正说明如何过滤掉答案......并且无法使其正常运作..

在C#中我可以这样做,其中xmlanswer是顶部的xml,但无法在android中找到它

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

4 个答案:

答案 0 :(得分:1)

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

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

val rootTag=XmlTag.getXmlRootTagOfXmlFileResourceId(context,xmlResId)

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

val rootTag=XmlTag.getXmlFromString(xmlString)

这里是代码:

/**
 * 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)
                            for (i in 0 until numberOfAttributes) {
                                val attrName = xmlParser.getAttributeName(i)
                                val attrValue = xmlParser.getAttributeValue(i)
                                attributes[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
                        if (currentTag != null)
                            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, xmlFileResourceId: Int): XmlTag? {
            val res = context.resources
            val xmlParser = res.getXml(xmlFileResourceId)
            return getXmlRootTagOfXmlPullParser(xmlParser)
        }
    }

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

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

}

答案 1 :(得分:0)

如果你想要使用jDom ......

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

PS:无法在Linux上运行......

答案 2 :(得分: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();

答案 3 :(得分: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();
    }
}