以下是我最近做项目总结的注意点,希望对一些对KXML解析不是很熟悉的人有所帮助。
解析如下xml文件的两种技术方法:
<?xml version="1.0" encoding="utf-8"?>
<response type="login" status="true" remark="">
<param name="username">admin</param>
<param name="token">admin:21232f297a57a5a743894a0e4a801fc3</param>
</response>
该XML文件是从服务端传输过来的
方法一、
InputStream is = null;
is=conn.openInputStream();
processCRListsXML(is);
public void processCRListsXML(InputStream input){
try{
InputStreamReader isr = new InputStreamReader( input ,"UTF-8");
KXmlParser parser=new KXmlParser();
parser.setInput(isr);
parser.next();
parser.require(KXmlParser.START_TAG, null, "response");
//当有属性时,输出属性
String attrName;
String attrValue;
if (parser.getAttributeCount() >= 1)
for (int i = 0; i < parser.getAttributeCount(); i++) {
// 输出属性名称
attrName=parser.getAttributeName(i);
// 输出属性值
attrValue=parser.getAttributeValue(i);
if(attrName.equals("type")){
// id=attrValue;
}else if(attrName.equals("status")){
}else if(attrName.equals("remark")){
}
System.out.println(attrName+"="+attrName);
}
String name="";
String value="";
while(parser.nextTag()!=KXmlParser.END_TAG){
name=parser.getName();
value=parser.nextText();
parser.require(KXmlParser.END_TAG, null, name);
}
parser.require(KXmlParser.END_TAG, null, "response");
parser.next();
parser.require(KXmlParser.END_DOCUMENT, null, null);
}catch(Exception ex){
ex.printStackTrace();
// System.out.println("=="+xml);
}
}
方法二、
DataInputStream dis = null;
dis = conn.openDataInputStream();
InputStreamReader isr= new InputStreamReader(input,"UTF-8");
StringBuffer sb= new StringBuffer();
int ic;
while((ic=isr.read())!=-1)
{
sb.append((char)ic);
}
String content = sb.toString();
processCRListsXML(content);
public void processCRListsXML(String xml){
try{
ByteArrayInputStream bin =new ByteArrayInputStream(xml.getBytes("UTF-8") );
InputStreamReader in = new InputStreamReader( bin ,"UTF-8");
KXmlParser parser=new KXmlParser();
parser.setInput(in);
parser.next();
parser.require(KXmlParser.START_TAG, null, "response");
//当有属性时,输出属性
String attrName;
String attrValue;
if (parser.getAttributeCount() >= 1)
for (int i = 0; i < parser.getAttributeCount(); i++) {
// 输出属性名称
attrName=parser.getAttributeName(i);
// 输出属性值
attrValue=parser.getAttributeValue(i);
if(attrName.equals("type")){
// id=attrValue;
}else if(attrName.equals("status")){
}else if(attrName.equals("remark")){
}
System.out.println(attrName+"="+attrName);
}
String name="";
String value="";
while(parser.nextTag()!=KXmlParser.END_TAG){
name=parser.getName();
value=parser.nextText();
parser.require(KXmlParser.END_TAG, null, name);
}
parser.require(KXmlParser.END_TAG, null, "response");
parser.next();
parser.require(KXmlParser.END_DOCUMENT, null, null);
in.close();
bin.close();
}catch(Exception ex){
ex.printStackTrace();
// System.out.println("=="+xml);
}
}
解析结构为:
type=type
status=status
remark=remark