有人能告诉我如何使用SAX解析存储在系统中的本地XML文件,并附带示例代码吗?还请告诉我在哪里可以找到相关信息。
答案 0 :(得分:19)
要从应用程序中的XML读取,请在项目内的res文件夹中创建一个名为“xml”的文件夹(小写)。将xml存储在这个新创建的文件夹中。要从资源加载XML,
XmlResourceParser myxml = mContext.getResources().getXml(R.xml.MyXml);//MyXml.xml is name of our xml in newly created xml folder, mContext is the current context
// Alternatively use: XmlResourceParser myxml = getContext().getResources().getXml(R.xml.MyXml);
myxml.next();//Get next parse event
int eventType = myxml.getEventType(); //Get current xml event i.e., START_DOCUMENT etc.
然后你可以开始处理包含在事件类型中的节点,属性等和文本,一旦处理完成后调用myxml.next()来获取下一个事件,即
String NodeValue;
while (eventType != XmlPullParser.END_DOCUMENT) //Keep going until end of xml document
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
//Start of XML, can check this with myxml.getName() in Log, see if your xml has read successfully
}
else if(eventType == XmlPullParser.START_TAG)
{
NodeValue = myxml.getName();//Start of a Node
if (NodeValue.equalsIgnoreCase("FirstNodeNameType"))
{
// use myxml.getAttributeValue(x); where x is the number
// of the attribute whose data you want to use for this node
}
if (NodeValue.equalsIgnoreCase("SecondNodeNameType"))
{
// use myxml.getAttributeValue(x); where x is the number
// of the attribute whose data you want to use for this node
}
//etc for each node name
}
else if(eventType == XmlPullParser.END_TAG)
{
//End of document
}
else if(eventType == XmlPullParser.TEXT)
{
//Any XML text
}
eventType = myxml.next(); //Get next event from xml parser
}
答案 1 :(得分:6)
package com.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.util.Log; import android.widget.Toast; public class FeedHandler extends DefaultHandler { StringBuilder sb = null; String ret = ""; boolean bStore = false; int howMany = 0; FeedHandler() { } String getResults() { return "XML parsed data.\nThere are [" + howMany + "] status updates\n\n" + ret; } @Override public void startDocument() throws SAXException { // initialize "list" } @Override public void endDocument() throws SAXException { } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { try { if (localName.equals("status")) { this.sb = new StringBuilder(""); bStore = true; } if (localName.equals("user")) { bStore = false; } if (localName.equals("text")) { this.sb = new StringBuilder(""); Log.i("sb ", sb+""); } if (localName.equals("created_at")) { this.sb = new StringBuilder(""); } } catch (Exception e) { Log.d("error in startElement", e.getStackTrace().toString()); } } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (bStore) { if (localName.equals("created_at")) { ret += "Date: " + sb.toString() + "\n"; sb = new StringBuilder(""); return; } if (localName.equals("user")) { bStore = true; } if (localName.equals("text")) { ret += "Post: " + sb.toString() + "\n\n"; sb = new StringBuilder(""); return; } } if (localName.equals("status")) { howMany++; bStore = false; } } @Override public void characters(char ch[], int start, int length) { if (bStore) { // System.out.println("start " +start+"length "+length); String theString = new String(ch, start, length); this.sb.append(theString+"start "+start+" length "+length); } } }
InputSource is = new InputSource(getResources().openRawResource(R.raw.my)); System.out.println("running xml file..... "); // create the factory SAXParserFactory factory = SAXParserFactory.newInstance(); // create a parser SAXParser parser = factory.newSAXParser(); // create the reader (scanner) XMLReader xmlreader = parser.getXMLReader(); // instantiate our handler FeedHandler fh = new FeedHandler(); // assign our handler xmlreader.setContentHandler(fh); // perform the synchronous parse xmlreader.parse(is); // should be done... let's display our results tvData.setText(fh.getResults());
答案 2 :(得分:1)
示例代码
创建documentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory。 newDocumentBuilder();
//实现必需的处理程序 公共类SaxParse扩展了DefaultHandler { } // saxParserFactory的新实例 SAXParserFactory factory = SAXParserFactory.newInstance(); // SAX PARSER的新实例 SAXParser saxparser = factory.newSAXParser(); //解析xml文档 SAXParser.parse(新文件(要解析的文件),新SAXXMLParserImpl());