使用SAXparser将信息获取多个元素(Android)

使用SAXparser将信息获取多个元素(Android),第1张

概述我是Android(和Java)的新用户,但现在我开始使用Web服务.因此,为了更好地理解如何解析XML,我开始尝试本教程:http://www.anddev.orgovice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html使用本示例中使用的XML:<outertag><innertagsampleattribute="i

我是Android(和Java)的新用户,但现在我开始使用Web服务.

因此,为了更好地理解如何解析XML,我开始尝试本教程:

http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html

使用本示例中使用的XML:

<outertag><innertag sampleattribute="innertagAttribute"><mytag>anddev.org rulez =)</mytag><tagwithnumber thenumber="1337"/></innertag></outertag>

我知道它是如何工作的(我想),但是如果XML是这样的:

<outertag><innertag sampleattribute="innertagAttribute"><mytag>anddev.org rulez =)</mytag><tagwithnumber thenumber="1337"/></innertag><innertag sampleattribute="innertagAttribute2"><mytag>something</mytag><tagwithnumber thenumber="14214"/></innertag></outertag>

为了获得各种元素的数据,需要在应用程序的类中进行哪些更改?

我很高兴提出建议…

完整的源代码:

> ParseXML.java

包org.anddev.androID.parsingxml;

导入java.net.URL;

导入javax.xml.parsers.SAXParser;
导入javax.xml.parsers.SAXParserFactory;

导入org.xml.sax.inputSource;
导入org.xml.sax.XMLReader;

导入androID.app.Activity;
导入androID.os.Bundle;
导入androID.util.Log;
导入androID.Widget.TextVIEw;

公共类ParsingXML扩展Activity {

private final String MY_DEBUG_TAG = "WeatherForcaster";/** Called when the activity is first created. */@OverrIDepublic voID onCreate(Bundle icicle) {    super.onCreate(icicle);    /* Create a new TextVIEw to display the parsingresult later. */    TextVIEw tv = new TextVIEw(this);    try {        /* Create a URL we want to load some xml-data from. */        URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");        /* 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. */        ParsedExampleDataSet parsedExampleDataSet =                                 myExampleHandler.getParsedData();        /* Set the result to be displayed in our GUI. */        tv.setText(parsedExampleDataSet.toString());    } catch (Exception e) {        /* display any Error to the GUI. */        tv.setText("Error: " + e.getMessage());        Log.e(MY_DEBUG_TAG, "WeatherqueryError", e);    }    /* display the TextVIEw. */    this.setContentVIEw(tv);}

}
> ExampleHandler

包org.anddev.androID.parsingxml;

导入org.xml.sax.Attributes;
导入org.xml.sax.SAXException;
导入org.xml.sax.helpers.DefaultHandler;

公共类ExampleHandler扩展DefaultHandler {

// ===========================================================// FIElds// ===========================================================private boolean in_outertag = false;private boolean in_innertag = false;private boolean in_mytag = false;private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();// ===========================================================// Getter & Setter// ===========================================================public ParsedExampleDataSet getParsedData() {    return this.myParsedExampleDataSet;}// ===========================================================// Methods// ===========================================================@OverrIDepublic voID startdocument() throws SAXException {    this.myParsedExampleDataSet = new ParsedExampleDataSet();}@OverrIDepublic voID enddocument() throws SAXException {    // nothing to do}/** Gets be called on opening Tags like:  * <tag>  * Can provIDe attribute(s), when xml was like: * <tag attribute="attributeValue">*/@OverrIDepublic voID startElement(String namespaceURI, String localname,        String qname, Attributes atts) throws SAXException {    if (localname.equals("outertag")) {        this.in_outertag = true;    }else if (localname.equals("innertag")) {        this.in_innertag = true;    }else if (localname.equals("mytag")) {        this.in_mytag = true;    }else if (localname.equals("tagwithnumber")) {        // Extract an Attribute        String attrValue = atts.getValue("thenumber");        int i = Integer.parseInt(attrValue);        myParsedExampleDataSet.setExtractedInt(i);    }}/** Gets be called on closing Tags like:  * </tag> */@OverrIDepublic voID endElement(String namespaceURI, String localname, String qname)        throws SAXException {    if (localname.equals("outertag")) {        this.in_outertag = false;    }else if (localname.equals("innertag")) {        this.in_innertag = false;    }else if (localname.equals("mytag")) {        this.in_mytag = false;    }else if (localname.equals("tagwithnumber")) {        // nothing to do here    }}/** Gets be called on the following structure:  * <tag>characters</tag> */@OverrIDepublic voID characters(char ch[], int start, int length) {    if(this.in_mytag){        myParsedExampleDataSet.setExtractedString(new String(ch, start, length));    }}

}
> ParsedExampleDataSet

包org.anddev.androID.parsingxml;

公共类ParsedExampleDataSet {
    私有字符串extractString = null;
    私人诠释extractInt = 0;

public String getExtractedString() {    return extractedString;}public voID setExtractedString(String extractedString) {    this.extractedString = extractedString;}public int getExtractedInt() {    return extractedInt;}public voID setExtractedInt(int extractedInt) {    this.extractedInt = extractedInt;}public String toString(){    return "ExtractedString = " + this.extractedString            + "nExtractedInt = " + this.extractedInt;}

}

解决方法:

问题解决了!

贝娄(Bellow)是包含有用信息的网站:

> https://stackoverflow.com/a/4828765
> https://stackoverflow.com/a/5709544
> http://as400samplecode.blogspot.com/2011/11/android-parse-xml-file-example-using.html
> http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html

我最初的问题是如何为要从XML提取的数据定义类.在弄清楚应该如何做(回顾JAVA编程的基本概念)之后,我将ExampleHandler返回的数据类型更改为ArrayList<“您要返回的数据类”.我在下面举一个例子:
>您要解析的XML示例:

<outertag><cartag type="Audi">    <itemtag name="model">A4</itemtag>    <itemtag name="color">Black</itemtag>    <itemtag name="year">2005</itemtag></cartag><cartag type="Honda">    <itemtag name="model">Civic</itemtag>    <itemtag name="color">Red</itemtag>    <itemtag name="year">2001</itemtag> </cartag> <cartag type="Seat">    <itemtag name="model">Leon</itemtag>    <itemtag name="color">White</itemtag>    <itemtag name="year">2009</itemtag> </cartag> </outertag>

因此,您应该在此处定义具有适当属性(字符串类型,模型,颜色,年份;),设置器和获取器的类“汽车”.

>我对XML的ExampleHandler的建议是:

公共类ExampleHandler扩展DefaultHandler {

// ===========================================================// FIElds// ===========================================================private int numberOfItems=3;    private boolean in_outertag = false;private boolean in_cartag = false;private boolean[] in_itemtag = new boolean[numberOfItems];Car newCar = new Car(); private ArrayList<Car> List = new ArrayList<Car>(); // ===========================================================// Getter & Setter// ===========================================================public ArrayList<Car> getParsedData() {    return this.List;}// ===========================================================// Methods// ===========================================================@OverrIDepublic voID startdocument() throws SAXException {    this.List = new ArrayList<Car>();}@OverrIDepublic voID enddocument() throws SAXException {    // nothing to do}/** Gets be called on opening Tags like:  * <tag>  * Can provIDe attribute(s), when xml was like: * <tag attribute="attributeValue">*/@OverrIDepublic voID startElement(String namespaceURI, String localname,        String qname, Attributes atts) throws SAXException {    if (localname.equals("outertag")) {        this.in_outertag = true;    }else if (localname.equals("cartag")) {        this.in_cartag = true;        newCar.setType(atts.getValue("type"));  //setType(...) is the setter defined in car class    }else if (localname.equals("itemtag")) {        if((atts.getValue("name")).equals("model")){            this.in_itemtag[0] = true;        }else if((atts.getValue("name")).equals("color")){            this.in_itemtag[1] = true;        }else if((atts.getValue("name")).equals("year")){            this.in_itemtag[2] = true;        }    }}/** Gets be called on closing Tags like:  * </tag> */@OverrIDepublic voID endElement(String namespaceURI, String localname, String qname)        throws SAXException {    if (localname.equals("outertag")) {        this.in_outertag = false;    }else if (localname.equals("cartag")) {        this.in_cartag = false;        Car carTemp = new Car();        carTemp.copy(newCar, carTemp);  //this method is defined on car class, and is used to copy the                                        //propertIEs of the car to another Object car to be added to the List        List.add(carTemp);    }else if (localname.equals("itemtag")){        if(in_itemtag[0]){            this.in_itemtag[0] = false;        }else if(in_itemtag[1]){            this.in_itemtag[1] = false;        }else if(in_itemtag[2]){            this.in_itemtag[2] = false;        }    }}/** Gets be called on the following structure:  * <tag>characters</tag> */@OverrIDepublic voID characters(char ch[], int start, int length) {    if(in_itemtag[0]){        newCar.setModel(new String(ch, start, length));    }else if(in_itemtag[1]){        newCar.setcolor(new String(ch, start, length));    }else if(in_itemtag[2]){        newCar.setYear(new String(ch, start, length));    }}

}

之后,您可以使用以下方法在“活动”中获取解析的数据:

...ArrayList<Car> ParsedData = myExampleHandler.getParsedData();...

我希望这可以帮助别人.

注意:我没有完全像这样测试过,但与我的解决方案几乎相同,因此应该可以工作…

对不起,我英语不好…

总结

以上是内存溢出为你收集整理的使用SAXparser将信息获取多个元素(Android)全部内容,希望文章能够帮你解决使用SAXparser将信息获取多个元素(Android)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1095602.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存