我有以下XML:
<ex>
<email>
xredhatx@gmail.com
</email>
<login_status>
TRUE
</login_status>
<category>
Personal
</category>
<subcategory>
Food
</subcategory>
<May>
50
</May>
</ex>
我有以下Java代码:
XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myParser = xmlFactoryObject.newPullParser();
myParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
InputStream inputstream = new ByteArrayInputStream(response.getBytes());
myParser.setInput(inputstream, null);
int event;
String text = null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (event) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
System.out.println("text"+text);
break;
case XmlPullParser.END_TAG:
String email = "email";
if(name.equals("email")){
email = myParser.getAttributeValue(null,"email");
System.out.println("emaildecrypt"+email);
}
break;
}
event = myParser.next();
}
// parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
然而,当我打印电子邮件时,我总是得到Null,我正在关注this tutorial,但我无法确定哪里出了问题?任何提示?
答案 0 :(得分:2)
您需要使用getText
代替getAttributeValue
:
email = myParser.getText();
System.out.println("emaildecrypt"+email);
这将返回当前标记中的文本,但请务必在case XmlPullParser.TEXT
中捕获(如您在评论中所述),但也要保留标记名称,以便您知道自己的位置:
int event;
String text = null;
try {
event = myParser.getEventType();
String name = ""
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
name = myParser.getName();
break;
case XmlPullParser.TEXT:
if(name.equals("email")){
text = myParser.getText();
System.out.println("text"+text);
}
break;
case XmlPullParser.END_TAG:
break;
}
event = myParser.next();
}
// parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
getAttributeValue
将返回当前代码的属性值。
如果电子邮件标签定义为:
<email address="asd@asd.com">
然后获取您将使用的地址值(仅适用于电子邮件标记):
myParser.getAttributeValue(null,"address");