这是 XML 解析器函数,它将 XML 作为字符串。
public class XMLParser {
public static void parser(String s) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
MyXMLhandler h = new MyXMLhandler();
xr.setContentHandler(h);
// Log.e("string", s);
xr.parse(new InputSource(new StringReader(s)));
} catch (ParserConfigurationException e) {
Log.e("ParserError", e.getMessage());
} catch (SAXException e) {
Log.e("SAXError", e.getMessage());
} catch (IOException e) {
Log.e("IOError", e.getMessage());
}
}
}
使用这个处理程序类来提取你需要的信息:
public class MyXMLhandler extends DefaultHandler {
private boolean language = false;
private boolean languagename = false;
private boolean contact = false;
private boolean update = false;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equalsIgnoreCase("language")) {
language = true;
} else if (localName.equalsIgnoreCase("languagename")) {
languagename = true;
} else if (localName.equalsIgnoreCase("contact")) {
contact = true;
} else if (localName.equalsIgnoreCase("update")) {
update = true;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("language")) {
language = false;
} else if (localName.equalsIgnoreCase("languagename")) {
languagename = false;
} else if (localName.equalsIgnoreCase("contact")) {
contact = false;
} else if (localName.equalsIgnoreCase("update")) {
update = false;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (language == true) {
String s = new String(ch, start, length);
Log.w("Language", s);
}
if (languagename == true) {
String s = new String(ch, start, length);
Log.w("Languagename", s);
}
if (contact == true) {
String s = new String(ch, start, length);
Log.w("contact", s);
}
if (update == true) {
String s = new String(ch, start, length);
Log.w("update", s);
}
}
}
使用上面的这个函数并修改它来解决你的问题