how to parse xml from EditText?
i try to build an application 开发者_如何学编程with xml parser.
ex : http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
but i want to parse xml file from EditText, how it work ?
Change this line:
xr.parse(new InputSource(sourceUrl.openStream()));
to
String xmlString = editText.getText().toString();
StringReader reader = new StringReader(xmlString);
xr.parse(new InputSource(reader));
You have several ways to parse XML, the most widely used being SAX and DOM. The choice is quite strategical as explained in this paper.
Here is a short explanation of SAX:
You will need some
import
s:import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import android.util.Xml;
Create your own XML SAX DefaultHandler:
class MySaxHandler extends DefaultHandler { // Override the methods of DefaultHandler that you need. // See [this link][3] to see these methods. // These methods are going to be called while the XML is read // and will allow you doing what you need with the content. // Two examples below: public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // This is called each time an openeing XML tag is read. // As the tagname is passed by parameter you know which tag it is. // You also have the attributes of the tag. // Example <mytag myelem="12"> will lead to a call of // this method with the parameters: // - localName = "mytag" // - attributes = { "myelem", "12" } } public void characters(char[] ch, int start, int length) throws SAXException { // This is called each time some text is read. // As an example, if you have <myTag>blabla</myTag> // this will be called with the parameter "blabla" // Warning 1: this is also called when linebreaks are read and the linebreaks are passed // Warning 2: you have to memorize the last open tag to determine what tag this text belongs to (I usually use a stack). } }
Extract the XML as a
String
from theEditText
. Let's call itxmlContent
Create and initialize your XML parser:
final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xmlContent.getBytes())); final MySaxHandler handler = new MySaxHandler();
And then, make the XML content to be read by the parser. This will lead your
MySaxHandler
to have its various method called while the reading is in progress.Xml.parse(reader, handler);
精彩评论