Android:如何获取特定 xml 标签下的值
我想获取 xml 文件的特定标签下的值(通过 url 访问),如下所示:
<SyncLoginResponse>
<Videos>
<Video>
<name>27/flv</name>
<title>scooter</title>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
<thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>
</Video>
<Video>
<name>26/flv</name>
<title>barsNtone</title>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
<thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
</Video>
</Videos>
<Slideshows>
<Slideshow>
<name>44</name>
<title>ProcessFlow</title>
<pages>4</pages>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>
</Slideshow>
</Slideshows>
<SyncLoginResponse>
如您所见,视频下有“名称”标签,幻灯片下也有“名称”标签以及“标题” ”和“网址”。我想获取幻灯片标签下的值。
到目前为止,我有以下代码:
EngagiaSync.java:
package com.example.engagiasync;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
public String FileName = "";
public String FileURL = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
tv.setText("...PARSE AND DOWNLOAD...");
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
url.openConnection();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
//tv.setText(parsedExampleDataSet.toString());
String currentFile;
String currentFileURL;
int x = 1;
Iterator i;
i = parsedExampleDataSet.iterator();
ParsedExampleDataSet dataItem;
while(i.hasNext()){
dataItem = (ParsedExampleDataSet) i.next();
tv.append("\nName:> " + dataItem.getName());
tv.append("\nTitle:> " + dataItem.getTitle());
tv.append("\nPages:> " + dataItem.getPages());
tv.append("\nFile:> " + dataItem.getUrl());
/*
int NumPages = Integer.parseInt(dataItem.getPages());
while( x <= NumPages ){
currentFile = dataItem.getName() + "-" + x + ".jpg";
currentFileURL = dataItem.getUrl() + currentFile;
tv.append("\nName: " + dataItem.getName());
tv.append("\nTitle: " + dataItem.getTitle());
tv.append("\nPages: " + NumPages );
tv.append("\nFile: " + currentFile);
startDownload(currentFile, currentFileURL);
x++;
}
*/
}
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
/* Display the TextView. */
this.setContentView(tv);
}
private void startDownload(String currentFile, String currentFileURL ){
new DownloadFileAsync().execute(currentFile, currentFileURL);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading files...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... strings) {
try {
String currentFile = strings[0];
String currentFileURL = strings[1];
File root = Environment.getExternalStorageDirectory();
URL u = new URL(currentFileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
ExampleHandler.java:
package com.example.engagiasync;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private StringBuilder mStringBuilder = new StringBuilder();
private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();
// ===========================================================
// Getter & Setter
// ===========================================================
public List<ParsedExampleDataSet> getParsedData() {
return this.mParsedDataSetList;
}
// ===========================================================
// Methods
// ===========================================================
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("Slideshow")) {
this.mParsedExampleDataSet = new ParsedExampleDataSet();
}
}
/** Gets be called on closing tags like:
* </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("Slideshow")) {
this.mParsedDataSetList.add(mParsedExampleDataSet);
}else if (localName.equals("name")) {
mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
}else if (localName.equals("title")) {
mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
}else if(localName.equals("pages")) {
mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
}else if(localName.equals("url")){
mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
}
mStringBuilder.setLength(0);
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {
mStringBuilder.append(ch, start, length);
}
}
ParsedExampleDataSet.java:
package com.example.engagiasync;
public class ParsedExampleDataSet {
private String name = null;
private String title = null;
private String pages = null;
private String url = null;
//name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//title
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
//pages
public String getPages(){
return pages;
}
public void setPages(String pages){
this.pages = pages;
}
//url
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url = url;
}
/*
public String toString(){
return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
}
*/
}
上面的代码返回以下结果用户界面:
...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/
我希望它是:
...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/
I want to get values under specific tags of my xml file (accessed via url) which look like this:
<SyncLoginResponse>
<Videos>
<Video>
<name>27/flv</name>
<title>scooter</title>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
<thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>
</Video>
<Video>
<name>26/flv</name>
<title>barsNtone</title>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
<thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
</Video>
</Videos>
<Slideshows>
<Slideshow>
<name>44</name>
<title>ProcessFlow</title>
<pages>4</pages>
<url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>
</Slideshow>
</Slideshows>
<SyncLoginResponse>
As you can see, there are "name" tags under video while there is also "name" tag under slideshow as well as "title" and "url". I want to get the values under slideshow tag.
So far, I have the following codes:
EngagiaSync.java:
package com.example.engagiasync;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
public String FileName = "";
public String FileURL = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
tv.setText("...PARSE AND DOWNLOAD...");
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
url.openConnection();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(url.openStream()));
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
//tv.setText(parsedExampleDataSet.toString());
String currentFile;
String currentFileURL;
int x = 1;
Iterator i;
i = parsedExampleDataSet.iterator();
ParsedExampleDataSet dataItem;
while(i.hasNext()){
dataItem = (ParsedExampleDataSet) i.next();
tv.append("\nName:> " + dataItem.getName());
tv.append("\nTitle:> " + dataItem.getTitle());
tv.append("\nPages:> " + dataItem.getPages());
tv.append("\nFile:> " + dataItem.getUrl());
/*
int NumPages = Integer.parseInt(dataItem.getPages());
while( x <= NumPages ){
currentFile = dataItem.getName() + "-" + x + ".jpg";
currentFileURL = dataItem.getUrl() + currentFile;
tv.append("\nName: " + dataItem.getName());
tv.append("\nTitle: " + dataItem.getTitle());
tv.append("\nPages: " + NumPages );
tv.append("\nFile: " + currentFile);
startDownload(currentFile, currentFileURL);
x++;
}
*/
}
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
}
/* Display the TextView. */
this.setContentView(tv);
}
private void startDownload(String currentFile, String currentFileURL ){
new DownloadFileAsync().execute(currentFile, currentFileURL);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading files...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... strings) {
try {
String currentFile = strings[0];
String currentFileURL = strings[1];
File root = Environment.getExternalStorageDirectory();
URL u = new URL(currentFileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
publishProgress("" + (int)((total*100)/lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
ExampleHandler.java:
package com.example.engagiasync;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ExampleHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private StringBuilder mStringBuilder = new StringBuilder();
private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();
// ===========================================================
// Getter & Setter
// ===========================================================
public List<ParsedExampleDataSet> getParsedData() {
return this.mParsedDataSetList;
}
// ===========================================================
// Methods
// ===========================================================
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
if (localName.equals("Slideshow")) {
this.mParsedExampleDataSet = new ParsedExampleDataSet();
}
}
/** Gets be called on closing tags like:
* </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("Slideshow")) {
this.mParsedDataSetList.add(mParsedExampleDataSet);
}else if (localName.equals("name")) {
mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
}else if (localName.equals("title")) {
mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
}else if(localName.equals("pages")) {
mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
}else if(localName.equals("url")){
mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
}
mStringBuilder.setLength(0);
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {
mStringBuilder.append(ch, start, length);
}
}
ParsedExampleDataSet.java:
package com.example.engagiasync;
public class ParsedExampleDataSet {
private String name = null;
private String title = null;
private String pages = null;
private String url = null;
//name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//title
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
//pages
public String getPages(){
return pages;
}
public void setPages(String pages){
this.pages = pages;
}
//url
public String getUrl(){
return url;
}
public void setUrl(String url){
this.url = url;
}
/*
public String toString(){
return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
}
*/
}
The codes above returns the following result in the UI:
...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/
In which I expect it to be:
...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 DOM 解析器而不是 SAX 解析器......
try using DOM parser instead of SAX parser....
这就是我的全部内容,如果您觉得它有用,请不要忘记将其标记为答案。
That is all my friend If you find it useful then dont forget to mark it as an answer.
嗨,
为父标签保留布尔变量,
并在 EndElement() 方法中检查父标签是否为真;
如果为真,则将该特定值存储到相应的变量中,仅此而已。
例如
,如果您有
两个变量作为结果 &布尔类型的自定义结果;
最初将它们标记为 false,
在 startElement() 方法中检查解析是否从 Result 元素开始,如果是,
则将其标记为 true。
&现在您知道您正在解析结果,因此您可以轻松识别结果中的变量
。
最好的问候,
〜阿努普
HI,
Keep boolean variables for the parent tags,
and do check in the EndElement() method that parent tag is true or not;
if it is true then store that particular value to corresponding variable that is all.
e.g.
if you have
take two variables as result & customresult of boolean type;
mark them as false initially,
check in the startElement() method whether parsing started with Result element if it so
then mark it as a true.
& now you know you are parsing result so you can easily recognize the variable in the
result.
Best Regards,
~Anup