如何将对象添加到另一个对象java的数组中

时间:2013-07-26 08:58:10

标签: java android object xml-parsing

我正在开发一款Android应用。我的应用程序有一个按钮,当我按下此按钮时,我将解析XML文件,将此文件的信息放在某个对象中,并将此对象显示在可扩展列表中。 我的XML文件也有这种结构:

<?xml version="1.0" encoding="UTF-8"?>
<Programs>
    <Program programNumber="1" imgURL="http://www.photovideolife.com/userfiles/Placeholder%2001.jpg" description="Lorem ipsum dolor sit er elit">
        <Episode pN="1" episodeNumber="1" transmissionName="Titolo" date="29 Giu 2013" time1="14:30" time2="" channel="Real Time" channelLogo="https://lh6.googleusercontent.com/-XSh-9ngYJu4/ThiY-xl2EeI/AAAAAAAABmc/iz04VpL5hOs/s800/realtime.png">
        </Episode>
        <Episode pN="1" episodeNumber="1" transmissionName="Titolo" date="29 Giu 2013" time1="" time2="16:30" channel="DMAX" channelLogo="http://tv.zam.it/canali/dmax.png">
        </Episode>
        <Episode pN="1" episodeNumber="2" transmissionName="Titolo" date="01 Lug 2013" time1="14:30" time2="" channel="Real Time" channelLogo="https://lh6.googleusercontent.com/-XSh-9ngYJu4/ThiY-xl2EeI/AAAAAAAABmc/iz04VpL5hOs/s800/realtime.png">
        </Episode>
        <Episode pN="1" episodeNumber="2" transmissionName="Titolo" date="01 Lug 2013" time1="" time2="16:30" channel="DMAX" channelLogo="http://tv.zam.it/canali/dmax.png">
        </Episode>
    </Program>
</Programs>

我制作了3个对象:剧集,节目和节目。我在这里发布实施:

Episode.java

public class Episode {
    String pN, episodeNumber, transmissionName, date, time1, time2, channel, channelLogo;

    public String getpN() {
        return pN;
    }

    public void setpN(String pN) {
        this.pN = pN;
    }

    public String getEpisodeNumber() {
        return episodeNumber;
    }

    public void setEpisodeNumber(String episodeNumber) {
        this.episodeNumber = episodeNumber;
    }

    public String getTransmissionName() {
        return transmissionName;
    }

    public void setTransmissionName(String transmissionName) {
        this.transmissionName = transmissionName;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime1() {
        return time1;
    }

    public void setTime1(String time1) {
        this.time1 = time1;
    }

    public String getTime2() {
        return time2;
    }

    public void setTime2(String time2) {
        this.time2 = time2;
    }

    public String getChannel() {
        return channel;
    }

    public void setChannel(String channel) {
        this.channel = channel;
    }

    public String getChannelLogo() {
        return channelLogo;
    }

    public void setChannelLogo(String channelLogo) {
        this.channelLogo = channelLogo;
    }

}

Program.java

public class Program {
    public Episode[] episodes;

    String programNumber, imgUrl, description;

    public Episode[] getEpisodes() {
        return episodes;
    }

    public void setEpisodes(Episode[] episodes) {
        this.episodes = episodes;
    }

    public String getProgramNumber() {
        return programNumber;
    }

    public void setProgramNumber(String programNumber) {
        this.programNumber = programNumber;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

Programs.java

public class Programs {
    public Program[] programs;

    public Program[] getPrograms() {
        return programs;
    }

    public void setPrograms(Program[] programs) {
        this.programs = programs;
    }
}

要解析我创建此类的XML文件:

XmlParser.java

import it.lucgian84.models.Episode;
import it.lucgian84.models.Program;
import it.lucgian84.models.Programs;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.renderscript.Element;
import android.util.Log;

public class XmlParser {
    private String xml;
    private Programs programs;
    private Program program = new Program();
    private Episode episode = new Episode();

    public XmlParser(String xml) {
        this.xml = xml;
    }

    public void parseXml() {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory
                    .newDocumentBuilder();
            Document document = documentBuilder.parse(new InputSource(
                    new ByteArrayInputStream(xml.getBytes("utf-8"))));
            document.getDocumentElement().normalize();
            NodeList nodeList = document.getElementsByTagName("Program");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node nodeItem = nodeList.item(i);
                if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) nodeItem;
                    program.setProgramNumber(((org.w3c.dom.Element) element)
                            .getAttribute("programNumber"));
                    program.setImgUrl(((org.w3c.dom.Element) element)
                            .getAttribute("imgUrl"));
                    program.setDescription(((org.w3c.dom.Element) element)
                            .getAttribute("description"));
                }
            }
            nodeList = document.getElementsByTagName("Episode");
             for (int i = 0; i < nodeList.getLength(); i++) {
                 Node nodeItem = nodeList.item(i);
                 if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
                     Element element = (Element) nodeItem;
                     episode.setpN(((org.w3c.dom.Element) element)
                                .getAttribute("pN"));
                     episode.setEpisodeNumber(((org.w3c.dom.Element) element)
                            .getAttribute("episodeNumber"));
                     episode.setTransmissionName(((org.w3c.dom.Element) element)
                            .getAttribute("transmissionName"));
                     episode.setDate(((org.w3c.dom.Element) element)
                            .getAttribute("date"));
                     episode.setTime1(((org.w3c.dom.Element) element)
                            .getAttribute("time1"));
                     episode.setTime2(((org.w3c.dom.Element) element)
                            .getAttribute("time2"));
                     episode.setChannel(((org.w3c.dom.Element) element)
                            .getAttribute("channel"));
                     episode.setChannelLogo(((org.w3c.dom.Element) element)
                            .getAttribute("channelLogo"));
                 }
             }
        } catch (Exception e) {
            Log.d("XML", "Exception: " + e);
        }
    }

}

我不确定如何将对象Episode插入到数组程序中,并将对象程序插入到数组程序中。 我希望你能帮助我找到这个问题的解决方案。 谢谢

1 个答案:

答案 0 :(得分:1)

List<Programs> programsList = new ArrayList<Programs>(); //create list of Programs
List<Program> programList = new ArrayList<Program>(); // create list of Program
programsList.add(new Program()); //object Program to the array Programs
programList.add(new Episode()); //insert the object Episode to the array Program

展开:

  

与您当前的实施:

public void parseXml() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document document = documentBuilder.parse(new InputSource(
                new ByteArrayInputStream(xml.getBytes("utf-8"))));
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("Program");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node nodeItem = nodeList.item(i);
            if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) nodeItem;

                Program program = new Program();

                program.setProgramNumber(((org.w3c.dom.Element) element)
                        .getAttribute("programNumber"));
                program.setImgUrl(((org.w3c.dom.Element) element)
                        .getAttribute("imgUrl"));
                program.setDescription(((org.w3c.dom.Element) element)
                        .getAttribute("description"));

                programsList.add(program);
            }
        }
        nodeList = document.getElementsByTagName("Episode");
         for (int i = 0; i < nodeList.getLength(); i++) {   
             Node nodeItem = nodeList.item(i);
             if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
                 Element element = (Element) nodeItem;

                 Episode episode = new Episode(); //creating new episode object

                 episode.setpN(((org.w3c.dom.Element) element)
                            .getAttribute("pN"));
                 episode.setEpisodeNumber(((org.w3c.dom.Element) element)
                        .getAttribute("episodeNumber"));
                 episode.setTransmissionName(((org.w3c.dom.Element) element)
                        .getAttribute("transmissionName"));
                 episode.setDate(((org.w3c.dom.Element) element)
                        .getAttribute("date"));
                 episode.setTime1(((org.w3c.dom.Element) element)
                        .getAttribute("time1"));
                 episode.setTime2(((org.w3c.dom.Element) element)
                        .getAttribute("time2"));
                 episode.setChannel(((org.w3c.dom.Element) element)
                        .getAttribute("channel"));
                 episode.setChannelLogo(((org.w3c.dom.Element) element)
                        .getAttribute("channelLogo"));

                 programList.add(episode);
             }
         }
    } catch (Exception e) {
        Log.d("XML", "Exception: " + e);
    }
}
  

另一种选择:

public void parseXml() {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory
                .newDocumentBuilder();
        Document document = documentBuilder.parse(new InputSource(
                new ByteArrayInputStream(xml.getBytes("utf-8"))));
        document.getDocumentElement().normalize();
        NodeList nodeList = document.getElementsByTagName("Program");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node nodeItem = nodeList.item(i);
            if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) nodeItem;

                String programNumber = ((org.w3c.dom.Element) element)
                        .getAttribute("programNumber");
                String imgUrl = ((org.w3c.dom.Element) element)
                            .getAttribute("imgUrl");
                String description = ((org.w3c.dom.Element) element)
                                .getAttribute("description");

                programsList.add(new Program(programNumber, imgUrl, description));
            }
        }
        nodeList = document.getElementsByTagName("Episode");
         for (int i = 0; i < nodeList.getLength(); i++) {   
             Node nodeItem = nodeList.item(i);
             if (nodeItem.getNodeType() == Node.ELEMENT_NODE) {
                 Element element = (Element) nodeItem;

                 String pN = ((org.w3c.dom.Element) element)
                            .getAttribute("pN");
                 String episodeNumber = ((org.w3c.dom.Element) element)
                                .getAttribute("episodeNumber");
                 String transmissionName =  ((org.w3c.dom.Element) element)
                                    .getAttribute("transmissionName");
                 String date =  ((org.w3c.dom.Element) element)
                                        .getAttribute("date");
                 String time1 = ((org.w3c.dom.Element) element)
                                            .getAttribute("time1");
                 String time2 = ((org.w3c.dom.Element) element)
                                                .getAttribute("time2");
                 String channel = ((org.w3c.dom.Element) element)
                                                    .getAttribute("channel");
                 String channelLogo = ((org.w3c.dom.Element) element)
                                                        .getAttribute("channelLogo");

                 programList.add(new Episode(pN, episodeNumber, transmissionName, date, time1, time2, channel, channelLogo));
             }
         }
    } catch (Exception e) {
        Log.d("XML", "Exception: " + e);
    }
}
  

使用alternatie方法,您必须在ProgramEpisode类中添加特定构造函数:

public class Program {
  public Program(String programNumber, String imgUrl, String description){
    setProgramNumber(programNumber);
    setImgUrl(imgUrl);
    setDescription(description);
  }

  ....the rest of your implementation...
}


public class Episode {
  public Episode(String pN, String episodeNumber, String transmissionName, String date, String time1, String time2, String channel, String channelLogo){
    setpN(pN);
    setEpisodeNumber(episodeNumber);
    setTransmissionName(transmissionName);
    setDate(date);
    setTime1(time1);
    setTime2(time2);
    setChannel(channel);
    setChannelLogo(channelLogo);
  }

  ....the rest of your implementation...
}
  • 我个人更喜欢替代方法,因为它更像是OO范式,更容易阅读(至少对我来说)并且更容易应对未来的变化

  • 代码如下:

    1. 对象ProgramEpisode已实例化
    2. 对象ProgramEpisode已填充
    3. 将对象ProgramEpisode添加到列表
  • 可以使用list.get(index)从列表中访问对象,并且可以在列表中更改对象,例如:((Program)list.get(index)).setDescription("my new description"),列表将会更新