gpt4 book ai didi

android - 如何解析android中的xml响应?

转载 作者:行者123 更新时间:2023-11-29 19:50:34 24 4
gpt4 key购买 nike

在我的应用程序中,我从 web 服务以 xml 格式接收以下 Httpresponse。

<?xml version="1.0" encoding="UTF-8"?>
<results>
<result>
<status>0</status>
<messageid>213123</messageid>
<destination>1234567890</destination>
</result>
</results>

我尝试解析以下格式的响应:

    private void parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
{
ArrayList<SMSResponse> products = null;
int eventType = parser.getEventType();
SMSResponse currentProduct = null;

while (eventType != XmlPullParser.END_DOCUMENT){
Log.e("ENTER-", "while loop");
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
products = new ArrayList<SMSResponse>();
Log.e("ENTER-", "swicth case -1");
break;
case XmlPullParser.START_TAG:

name = parser.getName();
Log.e("start name", name);
if(name.equals("results"))
{
Log.e("start name", name);
}
else if(name.equals("result"))
{
Log.e("start name", name);
currentProduct = new SMSResponse();
}
else if(name.equals("status"))
{
Log.e("start name", name);
System.out.println("status value==");
currentProduct.status = parser.getProperty(name).toString();

}
else if(name.equals("messageid"))
{
Log.e("start name", name);
System.out.println("messageid value=="+ parser.getProperty(name));
currentProduct.messageid = parser.getProperty(name).toString();
}
else if(name.equals("destination"))
{
Log.e("start name", name);
System.out.println("destination value=="+ parser.getProperty(name));
currentProduct.destination = parser.getProperty(name).toString();
}

break;
case XmlPullParser.END_TAG:
name = parser.getName();
Log.e("end name", name);
// Log.e("ENTER-", "switch case-3");
if (name.equalsIgnoreCase("results") ){
Log.e("end name", name);
products.add(currentProduct);
}
}
eventType = parser.next();
}


Log.e("Array", products.toString());

// printProducts(products);
}

但我得到的值是空响应。

如何提取 xml header 的值?

请帮助!提前致谢!

最佳答案

以下是处理 XML 操作的代码 fragment 。到目前为止,我正在使用 XML 解析器类,我们构建并循环遍历每个 XML 元素并获取子数据。

static final String KEY_RESULT = "result"; // parent node
static final String KEY_STATUS = "status";
static final String KEY_MESSAGE_ID = "messageid";
static final String KEY_DESC = "description";

XMLParser parser = new XMLParser();
//xml getting from url
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element

NodeList nl = doc.getElementsByTagName(KEY_RESULT);

// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
String name = parser.getValue(e, KEY_STATUS); // name child value
String cost = parser.getValue(e, KEY_MESSAGE_ID); // cost child value
String description = parser.getValue(e, KEY_DESC); // description child value
}

关于android - 如何解析android中的xml响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37178439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com