【发布时间】:2015-05-24 08:28:17
【问题描述】:
这是我的方法:
public void Read() {
try{
File fXmlFile = new File("C://Students.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("student");
Student s = new Student(); // Creating a new object
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
s.First_Name = eElement.getElementsByTagName("firstname").item(0).getTextContent();
Student.Last_Name = eElement.getElementsByTagName("lastname").item(0).getTextContent();
Student.ID = eElement.getAttribute("id");
Student.Spec = eElement.getElementsByTagName("spec").item(0).getTextContent();
Student.Course = eElement.getElementsByTagName("course").item(0).getTextContent();
Student.Ratingstr = eElement.getElementsByTagName("rating").item(0).getTextContent();
students.add(new Student());
}
}
}catch(Exception e){}
}
public static void main(String argv[]){
Student y = new Student();
y.Read();
}
这些是我的类字段:
ArrayList<Student> students = new ArrayList<>();
public static String First_Name;
public static String Last_Name;
public static String ID;
public static String Spec;
public static String Course;
public static String Ratingstr;
public float Rating;
为什么我要填充第二个“s”对象或第二个学生而不是第一个? 我的意思是当我在第一个周期中用我的第一个学生对象编写第一个索引时,我需要用第二个学生填充第二个索引,但我只用第二个学生填充第一个和第二个索引。我在第二个循环中覆盖了第一个索引。这是为什么呢?
【问题讨论】:
-
你的问题不清楚。您能否重新构建它以明确您的要求?
-
这篇文章看起来更像是手机上的短信,而不是 SO 上的问题。
-
不要像这样编辑你的问题......stackoverflow.com/help/asking
-
还...检查我的答案,看看为什么您的方法不起作用...
-
@Hristo,请不要将您的问题重复到其他问题中以深入了解进一步的答案 - 而是发布新问题(如果您不能,此评论的第一部分仍然适用) .
标签: java loops arraylist cycle