0

我正在尝试从 xml 字符串中读取数据并使用 setter getter 方法设置相应的标记元素,但我的 xml 在 xml 文件中显示格式错误。我在这里做错了什么是我的代码。

在 oncreate..

    SAXHelper2 sh = null;

    try {

        sh = new SAXHelper2(newxml);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

     sh.parseContent("");

    return null; 
}

}

 /* 
 * 
 */


class SAXHelper2 {


    private String data;
    StringBuffer chars = new StringBuffer();


    public SAXHelper2(String xmlstring) throws MalformedURLException {
        this.data = new String(xmlstring);
    }


    DefaultHandler handler = new DefaultHandler();

    public RSSHandler parseContent(String parseContent) {
        RSSHandler df = new RSSHandler();

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(new InputSource(newxml), new RSSHandler());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return df;
    }


    class RSSHandler extends DefaultHandler {

        private ComptePost currentPost = new ComptePost();

        StringBuffer chars = new StringBuffer();

        public void startElement(String uri, String localName, String qName, Attributes atts) {

            chars = new StringBuffer();
            if (localName.equalsIgnoreCase("comptes")) {

            }
        }

     DefaultHandler handler = new DefaultHandler() {

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {

            if (localName.equalsIgnoreCase("numCompte")
                    && currentPost.getNumComtpe() == null) {
                System.out.println("Post: "+currentPost.getNumComtpe());
                Log.i("numCompte", currentPost.getNumComtpe());
                currentPost.setNumComtpe(chars.toString());


            }
            if (localName.equalsIgnoreCase("authCompte")
                    && currentPost.getAuthCompte() == null) {
                currentPost.setAuthCompte(chars.toString());

            }
            if (localName.equalsIgnoreCase("typeCompte")
                    && currentPost.getTypeCompte() == null) {
                currentPost.setTypeCompte(chars.toString());


            }
            if (localName.equalsIgnoreCase("libelleCompte")
                    && currentPost.getLibelleCompte()== null) {
                currentPost.setLibelleCompte(chars.toString());
            }

            if (localName.equalsIgnoreCase("soldeCompte")
                    && currentPost.getSoldeCompte() == null) {
                currentPost.setSoldeCompte(chars.toString());
            }



            if (localName.equalsIgnoreCase("deviseCompte")
                    && currentPost.getDeviseCompte() == null) {
                currentPost.setDeviseCompte(chars.toString());


            }
            if (localName.equalsIgnoreCase("dateSolde")
                    && currentPost.getDateSolde()== null) {
                currentPost.setDateSolde(chars.toString());
            }

            if (localName.equalsIgnoreCase("droitVirement")
                    && currentPost.getDroitVirement()== null) {
                currentPost.setDroitVirement(chars.toString());
            }


            if (localName.equalsIgnoreCase("carteBancaire")
                    && currentPost.getCarteBancaire()== null) {
                currentPost.setCarteBancaire(chars.toString());
            }

            if (localName.equalsIgnoreCase("debitMin")
                    && currentPost.getDebitMin()== null) {
                currentPost.setDebitMin(chars.toString());
            }


            if (localName.equalsIgnoreCase("debitMax")
                    && currentPost.getDebitMax()== null) {
                currentPost.setDebitMax(chars.toString());
            }


            if (localName.equalsIgnoreCase("creditMin")
                    && currentPost.getCreditMin()== null) {
                currentPost.setCreditMin(chars.toString());
            }


            if (localName.equalsIgnoreCase("creditMax")
                    && currentPost.getCreditMax()== null) {
                currentPost.setCreditMax(chars.toString());
            }

            if (localName.equalsIgnoreCase("echeanceMax")
                    && currentPost.getEcheanceMax()== null) {
                currentPost.setEcheanceMax(chars.toString());
            }



            if (localName.equalsIgnoreCase("comptes")) {
                PostList.add(currentPost);
                currentPost = new ComptePost();
            }

        }


        @Override
        public void characters(char ch[], int start, int length) {
            chars.append(new String(ch, start, length));
        }

     };

    }


}

java.io.IOException:无法打开原因:java.net.MalformedURLException:找不到协议:

04-05 15:24:52.699: W/System.err(4784):     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:760)
04-05 15:24:52.703: W/System.err(4784):     at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:289)
04-05 15:24:52.707: W/System.err(4784):     at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
04-05 15:24:52.707: W/System.err(4784):     at .details.CompteDetails$SAXHelper2.parseContent(CompteDetails.java:222)
04-05 15:24:52.707: W/System.err(4784):     at .details.CompteDetails$loadingTask.doInBackground(CompteDetails.java:193)
04-05 15:24:52.710: W/System.err(4784):     at .details.CompteDetails$loadingTask.doInBackground(CompteDetails.java:1)
04-05 15:24:52.710: W/System.err(4784):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-05 15:24:52.710: W/System.err(4784):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
04-05 15:24:52.714: W/System.err(4784):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
04-05 15:24:52.714: W/System.err(4784):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
04-05 15:24:52.714: W/System.err(4784):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
04-05 15:24:52.718: W/System.err(4784):     at java.lang.Thread.run(Thread.java:1019)
04-05 15:24:52.718: W/System.err(4784):     at java.net.URL.<init>(URL.java:273)
04-05 15:24:52.722: W/System.err(4784):     at java.net.URL.<init>(URL.java:157)
04-05 15:24:52.722: W/System.err(4784):     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
4

2 回答 2

0

这将按预期工作

类型.java

package com.example.test;

public class Type
{
    private String lory;
    private String car;

    public String getLory()
    {
        return lory;
    }

    public void setLory(String lory)
    {
        this.lory = lory;
    }

    public String getCar()
    {
        return car;
    }

    public void setCar(String car)
    {
        this.car = car;
    }

    @Override
    public String toString()
    {
        return "Lory : " + this.lory + "\nCar : " + this.car;
    }

    public String getDetails()
    {
        String result = "Lory : " + this.lory + "\nCar : " + this.car;
        return result;
    }
}

SAXXMLHandler.java

package com.example.test;

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 SAXXMLHandler extends DefaultHandler
{
    private List<Type> types;
    private String tempVal;
    private Type tempType;

    public SAXXMLHandler()
    {
        types = new ArrayList<Type>();
    }

    public List<Type> getTypes()
    {
        return types;
    }

    // Event Handlers
    @Override
    public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) throws SAXException
    {
        // reset
        tempVal = "";
        if ( qualifiedName.equalsIgnoreCase("data") )
        {
            // create a new instance of type
            tempType = new Type();
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        tempVal = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qualifiedName) throws SAXException
    {
        if ( qualifiedName.equalsIgnoreCase("type") )
        {
            // add it to the list and create new instance
            types.add(tempType);
            tempType = new Type();
        }
        else if ( qualifiedName.equalsIgnoreCase("lory") )
        {
            tempType.setLory(tempVal);
        }
        else if ( qualifiedName.equalsIgnoreCase("car") )
        {
            tempType.setCar(tempVal);
        }
    }
}

SAXXMLParser.java

package com.example.test;

import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class SAXXMLParser
{
    public static List<Type> parse(InputStream is)
    {
        List<Type> types = null;
        try
        {
            // create a XMLReader from SAXParser
            XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            // create a SAXXMLHandler
            SAXXMLHandler saxHandler = new SAXXMLHandler();
            // store handler in XMLReader
            xmlReader.setContentHandler(saxHandler);
            // the process starts
            xmlReader.parse(new InputSource(is));
            // get the `Type list`
            types = saxHandler.getTypes();
        }
        catch ( Exception ex )
        {
            Log.d("XML", "SAXXMLParser: parse() failed");
        }
        // return Type list
        return types;
    }
}

SAXParserActivity.java

package com.example.test;

import java.io.ByteArrayInputStream;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class SAXParserActivity extends Activity implements OnClickListener
{
    Button button;
    List<Type> types = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <data> <type> <lory>vroom</lory> <car>crack</car> </type> <type> <lory>doom</lory> <car>chack</car> </type> </data>";
        types = SAXXMLParser.parse(new ByteArrayInputStream(xml.getBytes()));
        Log.d("SSDDSD", "Length : " + "" + types.size());
        for ( Type type : types )
        {
            Log.d("SAXParserActivity", type.toString());
            Toast.makeText(getApplicationContext(), type.toString(), Toast.LENGTH_SHORT).show();
        }
    }
}

主要的.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dip" >
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Parse XML Using SAX" />
</LinearLayout>

您可以在 LogCat 和 Toast 中看到输出。

于 2013-04-05T12:57:35.970 回答
0

尝试使用 xmlPullParser 而不是 Sax!像这样:

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 XmlPullParserCdb {

public static void parse(String dados) throws XmlPullParserException, IOException {
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XmlPullParser xpp = factory.newPullParser();

    xpp.setInput(new StringReader(dados));
    int eventType = xpp.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_DOCUMENT) {
            System.out.println("Start document");
        } else if (eventType == XmlPullParser.END_DOCUMENT) {
            System.out.println("End 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();
    }
}

}

于 2013-04-26T02:02:52.900 回答