我尝试使用xml解析器构建应用程序。
ex:http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
但是我想从EditText解析xml文件,它是如何工作的?
答案 0 :(得分:1)
更改此行:
xr.parse(new InputSource(sourceUrl.openStream()));
到
String xmlString = editText.getText().toString();
StringReader reader = new StringReader(xmlString);
xr.parse(new InputSource(reader));
答案 1 :(得分:0)
您有几种方法可以解析XML,最常用的是SAX和DOM。选择非常具有战略性as explained in this paper。
以下是SAX的简短说明:
您需要一些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;
创建自己的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).
}
}
从String
中将XML解压缩为EditText
。我们称之为xmlContent
创建并初始化XML解析器:
final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xmlContent.getBytes()));
final MySaxHandler handler = new MySaxHandler();
然后,让解析器读取XML内容。这将导致您的MySaxHandler
在阅读过程中调用其各种方法。
Xml.parse(reader, handler);