如何在本地文件上使用XMLPullParser [英] How to use XMLPullParser on a local file
问题描述
我正在使用XMLPullParser来读取资产文件夹中的本地XML文件,该教程的代码位于android开发人员网站上:
I am using the XMLPullParser to read a local XML file in the assets folder, the code for the tutorial is on the android developers website:
链接: http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
代码:
import java.io.IOException;
import java.io.StringReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class SimpleXmlPullApp
{
public static void main (String args[])
throws XmlPullParserException, IOException
{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
}`
我意识到StringReader是我必须替换的东西,但是我应该用它替换什么以便可以使用本地文件?
I realise that the StringReader is what I have to replace, but what do I replace it with so that I can use the local file?
推荐答案
如果xml文件位于资产文件夹中,则可以按以下方式进行检索:
If the xml file is in the assets folder, it can be retrieved like this:
使用context.getAssets().openXmlResourceParser(String filename)
.它返回一个XmlResourceParser
,在其示例中为XmlPullParser
的实现.如果文件位于assets/subfolder/file.xml
中,则filename参数将为"subfolder/file.xml"
.
Use context.getAssets().openXmlResourceParser(String filename)
. It returns an XmlResourceParser
which is an implementation of the XmlPullParser
in their example. If the file is in assets/subfolder/file.xml
, the filename parameter would be "subfolder/file.xml"
.
要考虑的另一件事是,您可以将其放在资源下的XML文件夹中,并将其检索为R.xml.filename:
The other thing to consider is that you can put it in the XML folder under resources and retrieve it as R.xml.filename:
res/xml/filename.xml
<?xml version="1.0" encoding="utf-8"?>
<credits>
<credit>one</credit>
<credit>two</credit>
</credits>
在Android活动中:
In the Android Activity:
final XmlResourceParser parser = getContext().getResources().getXml(R.xml.filename);
这篇关于如何在本地文件上使用XMLPullParser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!