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

标签 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、Program 和 Programs。我在这里发布实现:

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;
    }

}

程序.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;
    }

}

程序.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 插入到数组 Program 中,以及如何将对象 Program 插入到数组 Programs 中。 我希望你能帮助我找到解决这个问题的方法。 谢谢

最佳答案

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

扩展:

with your current implementation:

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);
    }
}

Another alternative:

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);
    }
}

With alternatie approach, then you have to add specific constructors in your Program and Episode classes:

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 范式并且更易于阅读(至少对我而言)并且更易于应对 future 的变化

  • 代码如下:

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

关于java - 如何将一个对象添加到另一个对象的数组中java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17877092/

相关文章:

java - 使用 Jsoup 仅删除 html 标签并保留标签内的文本

android - 获取 Assets ();从另一个类(class)

android - RxAndroid 迁移 asyncTask 最佳实践

javascript - 在回调 : why. 中更改对象时出现奇怪的行为 ..?

java - Java 的 IPv4/IPv6 网络计算和验证?

java - 如何获取 HashMap 中特定值的键?

android - Jetpack 撰写 : Hoisitng click state from DropDownItems to DropDownMenu

java - 返回 Ljava.lang.Object 的字符串值

arrays - 更新嵌套在 mongodb 对象数组中的字符串数组

java - 哪个 Swing 布局管理器可以获得我想要的布局?