在Android中使用Sax解析本地XML文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2728064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing local XML file using Sax in Android
提问by apoorva
Can anyone tell me how to parse a local XML file stored in the system using SAX, with an example code? Please also tell me where can I find information on that.
谁能通过示例代码告诉我如何使用 SAX 解析存储在系统中的本地 XML 文件?还请告诉我在哪里可以找到相关信息。
回答by Steven
To read from XML in your app, create a folder in your res folder inside your project called "xml" (lower case). Store your xml in this newly created folder. To load the XML from your resources,
要在您的应用程序中读取 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.
You can then start to process nodes, attributes etc and text contained within by casing the event type, once processed call myxml.next() to get the next event, i.e.,
然后,您可以开始处理节点、属性等和包含在事件类型中的文本,处理后调用 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
}
回答by Pragna
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());
回答by srinivas Nidadavolu
sample code
示例代码
Create documentBuilderFactory
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- Create DocumentBuilder
DocumentBuilder builder=factory. newDocumentBuilder();
- get input stream
ClassLoader cls=DomReader.class.getClassLoader();
InputStream is=cls.getResourceAsStream("xml file");
- parse xml file and get Document object by calling parse method on DocumentBuilder object. Document document=builder.parse(is);
- Traverse dom tree using document object. SAX: Simple xml parsing. It parses node by node Traversing is from top to bottom Low memory usage Back navigation is not possible with sax.
//implementing required handlers public class SaxParse extends DefaultHandler{ } //new instance of saxParserFactory SAXParserFactory factory=SAXParserFactory.newInstance(); //NEW INSTANCE OF SAX PARSER SAXParser saxparser=factory.newSAXParser(); //Parsing xml document SAXParser.parse(new File(file to be parsed), new SAXXMLParserImpl());
创建文档生成器工厂
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- 创建文档生成器
DocumentBuilder 构建器=工厂。newDocumentBuilder();
- 获取输入流 ClassLoader cls=DomReader.class.getClassLoader(); InputStream is=cls.getResourceAsStream("xml 文件");
- 通过调用 DocumentBuilder 对象上的 parse 方法解析 xml 文件并获取 Document 对象。文档 document=builder.parse(is);
- 使用文档对象遍历 dom 树。SAX:简单的 xml 解析。它逐个节点解析 从上到下遍历 内存使用率低 使用 sax 无法返回导航。
//实现所需的处理程序 public class SaxParse extends DefaultHandler{ } // saxParserFactory 的新实例 SAXParserFactory factory=SAXParserFactory.newInstance(); //SAX 解析器的新实例 SAXParser saxparser=factory.newSAXParser(); //解析xml文档 SAXParser.parse(new File(file to be parsed), new SAXXMLParserImpl());