如何将 XML 读取到 Java 中的 POJO 列表? [英] How to read XML to a list of POJOs in Java?

查看:32
本文介绍了如何将 XML 读取到 Java 中的 POJO 列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XML 新手,我正在尝试读取 XML 页面并将其内容存储在数组列表中.

I'm new to XML and im trying to read in an XML page and store its contents in an arraylist.

到目前为止,我似乎已经能够用第一个内容填充数组列表,因为当我尝试使用 isEmpty 时,它返回 false.所以肯定有东西.但是,当我尝试调用覆盖的 tostring 方法时,甚至尝试为此调用任何单个类别时,它只会返回空?

So far i seem to have been able to get the arraylist filled with the first content, as when i tried an isEmpty, it returned false. so there is definitely containing something. However, when i try to call the overided tostring method, or even try to call any individual category for that matter, it just returns empty?

有人可以帮忙吗?

这是我使用的代码:

package test;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

   public static void main(String[] args) {
      ArrayList<Anime> list = new ArrayList<Anime>();
      try {
         File inputFile = new File("c:\\code\\ad\\XMLDB.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);
         doc.getDocumentElement().normalize();
         System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("Anime");
         System.out.println("----------------------------");

         for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) nNode;
               list.add(new Anime(eElement.getAttribute("ID"),
                                  eElement.getAttribute("name"),
                                  eElement.getAttribute("altname"),
                                  eElement.getAttribute("seasons"),
                                  eElement.getAttribute("episodes"),
                                  eElement.getAttribute("status"),
                                  eElement.getAttribute("DS"),
                                  eElement.getAttribute("have"),
                                  eElement.getAttribute("left"),
                                  eElement.getAttribute("plot"),
                                  eElement.getAttribute("connect"),
                                  eElement.getAttribute("image")));
               System.out.println(list.get(0).toString());
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

arraylist 属于动漫类型,这里是一个类:

the arraylist is of type anime, a class here:

    package test;

class Anime{
    private String ID;
    private String name;
    private String altname;
    private String seasons;
    private String episodes;
    private String status;
    private String DS;
    private String have;
    private String left;
    private String plot;
    private String connect;
    private String image;

    public Anime(String ID, 
                 String name,
                 String altname,
                 String seasons,
                 String episodes,
                 String status,
                 String DS,
                 String have,
                 String left,
                 String plot,
                 String connect,
                 String image) {
        this.ID = ID;
        this.name = name;
        this.altname = altname;
        this.seasons = seasons;
        this.episodes = episodes;
        this.status = status;
        this.DS = DS;
        this.have = have;
        this.left = left;
        this.plot = plot;
        this.connect = connect;
        this.image = image;
    }

/*
 getters and setters here...
*/
    @Override
    public String toString() {
        return "Anime [ID=" + ID + 
               ", name=" + name + 
               ", altname=" + altname + 
               ", seasons=" + seasons + 
               ", episodes=" + episodes + 
               ", status=" + status + 
               ", DS=" + DS + 
               ", have=" + have + 
               ", left=" + left + 
               ", plot=" + plot + 
               ", connect=" + connect + 
               ", image=" + image + "]";
    }
}

最后,这里是xml:

<?xml version="1.0" encoding="UTF-8"?>
<Anime>
    <record ID="BL1">
        <name>Bleach</name>
        <altname>Burichi</altname>
        <seasons>16</seasons>
        <episodes>366</episodes>
        <status>Finished</status>
        <sound>Dubbed</sound>
        <have>All</have>
        <left>-/-</left>
        <plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
        <connect>Bleach movies</connect>
        <image>images/bleach.jpg</image>
    </record>
</Anime>

非常感谢您的帮助,谢谢

any help would be greatly appreciated, thank you

推荐答案

基本上你对 w3c dom xml 元素的理解是错误的.name:"、altname"等不是Animie"元素的属性.那些是record"节点的子节点".所以首先你必须通过迭代Animie"元素的子节点来获取record"节点.然后您可以遍历记录"元素的子节点,以便填充您的动漫对象.

Hi basically your understanding about the w3c dom xml element is wrong. "name:, "altname" etc are not attributes of "Animie" element. those are "child nodes" of "record" node. So first you have to fetch "record" node by iterating child nodes of "Animie" element. Then you can iterate through the child nodes of "record" element so that you can populate your Anime object.

这是您的xmlmx 类的简单实现.我不得不使用地图,因为您省略了 setter 方法,这可以通过尝试修复您头脑中的 xml 概念来改进.

Here's a simple implementation of your "xmlmx class that works. I had to use a map because you have ommitted the setter methods, this can be improved just trying to fix the xml concepts in your head.

用这个替换你的类.

package test;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

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

import com.sun.org.apache.xerces.internal.dom.DeferredElementImpl;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class xmlmx {

    public static void main(String[] args) {
        ArrayList<Anime> list = new ArrayList<Anime>();
        try {
            File inputFile = new File("test.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());

            Node recordNode = null;
            NodeList childNodes = doc.getFirstChild().getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                if (childNodes.item(i).getNodeName().equals("record")) {
                    recordNode = childNodes.item(i);
                    break;
                }
            }
            System.out.println("----------------------------");


            Map<String, String> map = new HashMap<>();
            if (recordNode != null) {
                NodeList subNodes = recordNode.getChildNodes();
                for (int i = 0; i < subNodes.getLength(); i++) {
                    if (subNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                        map.put(subNodes.item(i).getNodeName(), subNodes.item(i).getTextContent());
                    }
                }
            }

            String id = ((DeferredElementImpl) recordNode).getAttribute("ID");
            list.add(new Anime(id,
                    map.get("name"),
                    map.get("altname"),
                    map.get("seasons"),
                    map.get("episodes"),
                    map.get("status"),
                    map.get("DS"),
                    map.get("have"),
                    map.get("left"),
                    map.get("plot"),
                    map.get("connect"),
                    map.get("image")));

            System.out.println(list.get(0));


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

这篇关于如何将 XML 读取到 Java 中的 POJO 列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆