我正在创建一个应用程序,在该应用程序中,我从服务器中获取包含特殊字符的xml,当我在android端解析它时,我得到了包含特殊字符串的单个字符串的不同字符串以下是生成的xml示例:
<field>
<option>Didn't Apply For Card,Do Not Want the Card,No</option>
<validation>NA</validation>
<field_name>self_closed</field_name>
</field>
这是我的代码:
String tagname,value = null,t_name;
t_name=table_name;
XmlPullParserFactory xmlPullParserFactory = null;
XmlPullParser xmlPullParser = null;
//System.out.println("In parse UI table name:"+table_name);
result=input_stream;
try {
xmlPullParserFactory = XmlPullParserFactory.newInstance();
xmlPullParserFactory.setNamespaceAware(true);
xmlPullParser = xmlPullParserFactory.newPullParser();
//System.out.println("Load file :"+result);
xmlPullParser.setInput(result,"UTF-8");
//xmlPullParser.defineEntityReplacementText("&","&");
int eventType = xmlPullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
tagname=xmlPullParser.getName();
if(eventType==XmlPullParser.START_TAG)
{
}
else if(eventType==XmlPullParser.TEXT)
{
value=xmlPullParser.getText();
if(value.isEmpty())
{
System.out.println("string is empty");
}
value=conversion.add_special_character(value);
System.out.println("value:"+value);
value=value.trim();
System.out.println(" text tag value :"+value);
}
else if(eventType==XmlPullParser.END_TAG)
{
if(tagname.equals("field"))
{
//System.out.println("field"+field+" table name:"+t_name);
dbController.insert_into_fields(field, t_name);
//database.insert_into_fields(field);
field.clear();
}
if(tagname.equals("field_name"))
{
field.put("field_name", value);
}
if(tagname.equals("type"))
{
field.put("input_type", value);
}
if(tagname.equals("label"))
{
field.put("label", value);
}
if(tagname.equals("option"))
{
//System.out.println("in option tag option:"+value);
field.put("option", value);
}
if(tagname.equals("validation"))
{
//System.out.println("In validation tag:"+value);
field.put("validation", value);
}
// System.out.println("Tag_name :"+tagname);
} // end of else end tag
eventType = xmlPullParser.nextToken();
}// end of while loop
dbController.close_database();
} // end of try
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
} // end of catch
当我解析它而不是将"没有申请卡"作为整个字符串时,我将其作为两个不同的字符串"没有"和t申请卡
尝试使用以下代码解析xml:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput("xml input stream", null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("field")) {
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("field")) {
} else if (tagname.equalsIgnoreCase("option")) {
System.out.println(text);
}
break;
default:
break;
}
}
} catch (XmlPullParserException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}