我嘗試用xml解析器構建應用程序。如何從EditText解析XML?
例如:http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
,但我想從EditText上解析XML文件,它是如何工作的?
我嘗試用xml解析器構建應用程序。如何從EditText解析XML?
例如:http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser
,但我想從EditText上解析XML文件,它是如何工作的?
您有幾種方法來解析XML,使用最廣泛的是SAX和DOM。選擇是相當戰略的。
這裏是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).
}
}
提取物將XML作爲String
EditText
。讓我們把它xmlContent
創建和初始化您的XML解析器:
final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(xmlContent.getBytes()));
final MySaxHandler handler = new MySaxHandler();
,然後做出解析器讀取XML內容。這會導致您的MySaxHandler
在讀數正在進行時調用其各種方法。
Xml.parse(reader, handler);
改變這一行:
xr.parse(new InputSource(sourceUrl.openStream()));
到
String xmlString = editText.getText().toString();
StringReader reader = new StringReader(xmlString);
xr.parse(new InputSource(reader));
此問題尚不清楚。你是什麼意思從EditText解析XML文件? – momo