gpt4 book ai didi

java - 读取xml文件时以对象形式获取数据

转载 作者:行者123 更新时间:2023-12-01 15:22:16 25 4
gpt4 key购买 nike

编写以下代码是为了从 xml 文件中获取数据。我认为它确实可以获取,但是是以对象形式。这是为什么?

package newpackage;

import java.io.File;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.LinkedList;

public class xmlParser {


private DocumentBuilder db;
private DocumentBuilderFactory dbf;
private Document dom;
private LinkedList list = new LinkedList();

public static void main(String args[]) {
xmlParser o = new xmlParser();
o.parseXML();
o.parseDocument();
o.print();
}

public void parseXML() { // getting a document builder
try {
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
dom = db.parse(new File("Details.xml"));
} catch(Exception exc) {
exc.printStackTrace();
}
}

public void parseDocument() { // get a list of student elements
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("Details");
if(nl != null && nl.getLength() > 0) {
for(int i=0;i<nl.getLength();i++) {
Element el = (Element)nl.item(i);
Details details = new Details();
details = details.getDetail(el);
list.add(details);
}
}
}

public void print() {
// list.iterator();
// while(!list.isEmpty()) {
// System.out.println(list.pop().toString());
// }

Iterator it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}

}
}

输出:

newpackage.Details@1ac3c08
newpackage.Details@9971ad
newpackage.Details@1f630dc
newpackage.Details@1c5c1

为什么即使在应用 toString 后我仍能获得对象形式的输出?

最佳答案

当您想要可读的输出时,您必须重写 newpackage.Details 类中的 toString() 方法;)

关于java - 读取xml文件时以对象形式获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10732712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com