解析XML不会在Android中占用退格

时间:2011-04-24 14:45:50

标签: android xml

我正在从Internet解析一些XML文件:

<data>
<News>
  <newsDate>15.04.11</newsDate>
  <newsTime>15h13</newsTime>
  <title>SHOP</title>
  <content>HORAIRES DE PAQUES ET NOUVEAUTE MERCHANDISING

Le SHOP vous informe de ses horaires d'ouverture pour la semaine du vendredi Saint :

Lundi 18.04 :  
de 09h00 à 11h00 et de 16h00 à 18h00

Mardi 19.04 :
de 09h00 à 11h00 et de 16h00 à 18h00

Vous pourrez y découvrir une nouveauté : L'autocollant pour vitre arrière de votre       voiture, avec le logo du club en dégradés de gris au prix de CHF 30.--

  </content>
  <pict>http://www.xxxxxxxx.ch/ressources/site/iphone/NEWS_DEFAULT1.png</pict>
 </News>
</data>

但是当我得到“内容”标签的内容时,我只得到第一部分“HORAIRES DE PAQUES ET NOUVEAUTE MERCHANDISING”。 你能告诉我为什么以及我能做些什么来获得全部内容?

由于

我的代码: 处理程序:

public class NewsHandler extends DefaultHandler{

Boolean currentElement = false;
String currentValue = null;
public static News newsList = null;

public static News getNews() {
    return newsList;
}

public static void setSitesList(News newsList) {
    NewsHandler.newsList = newsList;
}

/** Called when tag starts ( ex:- <name>AndroidPeople</name> 
 * -- <name> )*/
@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {

    currentElement = true;
    // --- le tag racine
    if (localName.equals("data"))
    {
        /** Start */ 
        newsList = new News();
    } /*else if (localName.equals("website")) {
        // Get attribute value 
        String attr = attributes.getValue("category");
        sitesList.setCategory(attr);
    }*/

}

/** Called when tag closing ( ex:- <name>AndroidPeople</name> 
 * -- </name> )*/
@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {

    currentElement = false;

    /** set value */ 
    if (localName.equalsIgnoreCase("title"))
        newsList.setTitle(currentValue);
    else if (localName.equalsIgnoreCase("newsDate"))
        newsList.setNewsDate(currentValue);
    else if (localName.equalsIgnoreCase("newsTime"))
        newsList.setNewsTime(currentValue);
    else if (localName.equalsIgnoreCase("content"))
        newsList.setContent(currentValue);
    else if (localName.equalsIgnoreCase("pict"))
        newsList.setPict(currentValue);

}

/** Called to get tag characters ( ex:- <name>AndroidPeople</name> 
 * -- to get AndroidPeople Character ) */
@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {

    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }

}

数据集

/** Contains getter and setter method for varialbles  */

公共课新闻{

///** Variables */
private ArrayList<String> newsDate= new ArrayList<String>();
private ArrayList<String> newsTime= new ArrayList<String>();
private ArrayList<String> title= new ArrayList<String>();
private ArrayList<String> content= new ArrayList<String>();
private ArrayList<String> pict= new ArrayList<String>();
public ArrayList<String> getNewsDate() {
    return newsDate;
}
public ArrayList<String> getNewsTime() {
    return newsTime;
}
public ArrayList<String> getTitle() {
    return title;
}
public ArrayList<String> getContent() {
    return content;
}
public ArrayList<String> getPict() {
    return pict;
}
public void setNewsDate(String newsDate) {
    this.newsDate.add(newsDate);
}
public void setNewsTime(String newsTime) {
    this.newsTime.add(newsTime);
}
public void setTitle(String title) {
    this.title.add(title);
}
public void setContent(String content) {
    this.content.add(content);
}
public void setPict(String pict) {
    this.pict.add(pict);
}

}

和“查看控制器”:

@Override
public void onCreate(Bundle savedInstanceState) {



    super.onCreate(savedInstanceState);
    setContentView(R.layout.newsview);



  //Récupération de la listview créée dans le fichier
    maListViewPerso = (ListView) findViewById(R.id.newslistview);

    //Création de la ArrayList qui nous permettra de remplire la listView
    ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();

    //On déclare la HashMap qui contiendra les informations pour un item
    HashMap<String, String> map;

// --- modif


        try {

            // Handling XML 
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            // Send URL to parse XML Tags 
            URL sourceUrl = new URL("http://www.xxxxxxxxxx.ch/ressources/site/xml/newsXml.xml");

            // Create handler to handle XML Tags ( extends DefaultHandler ) 
            NewsHandler myXMLHandler = new NewsHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        // Get result from MyXMLHandler SitlesList Object 
        newsList = NewsHandler.newsList;



        // Set the result text in textview and add it to layout 
        for (int i = 0; i < newsList.getTitle().size(); i++) {


            map = new HashMap<String, String>();
            map.put("title", newsList.getTitle().get(i));
            map.put("date", newsList.getNewsDate().get(i));
            map.put("time", newsList.getNewsTime().get(i));
            map.put("content", newsList.getContent().get(i));
            map.put("img", String.valueOf(R.drawable.joueurs));
            listItem.add(map);


        }

        //Création d'un SimpleAdapter qui se chargera de mettre les items présent dans notre list (listItem) dans la vue affichageitem
        SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.newscell,
               new String[] {"img", "title", "date", "time"}, new int[] {R.id.img, R.id.title, R.id.date, R.id.time});

        //On attribut à notre listView l'adapter que l'on vient de créer
        maListViewPerso.setAdapter(mSchedule);

        //Enfin on met un écouteur d'évènement sur notre listView
        maListViewPerso.setOnItemClickListener(new OnItemClickListener() {
            @Override
            @SuppressWarnings("unchecked")
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                //on récupère la HashMap contenant les infos de notre item (titre, description, img)
                HashMap<String, String> map = (HashMap<String, String>) maListViewPerso.getItemAtPosition(position);
                // Navigation vers un autre ecran
                System.out.println(map.get("content"));
                Intent intent = new Intent(NewsViewController.this, NewsDetailViewController.class);
                intent.putExtra("title", map.get("title"));
                intent.putExtra("content", map.get("content"));
                startActivity(intent);

            }
         });



     }

2 个答案:

答案 0 :(得分:3)

在对标记的startElementendElement调用之间,解析器可能会对包含文本的部分内容重复调用characters

您应该在characters方法中初始化StringBuffer字段,而不是简单地将字符转换为startElement方法中的字符串,将所有字符串复制到它在characters方法中,然后在String方法中获取endElement值。

答案 1 :(得分:0)

您假设每个元素只有一个文本节点。这是不正确的。请将所有文本节点附加在一起以获取元素内的全文。