使JDOM动态添加新元素

时间:2015-10-01 05:41:55

标签: java jdom

我试图通过不添加新学生并多次编写Element eltFirstName = new Element("FirstName");和lastname来使这段代码更具动态性,无论如何通过for循环实现而不使用sax。

public class javaForm extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        Element eltRoot = new Element("Students");

        Element eltStudent = new Element("Student");
        Element eltFirstName = new Element("FirstName");
        eltFirstName.addContent("Mike");
        Element eltLastName = new Element("LastName");
        eltLastName.addContent("dan");

        eltStudent.addContent(eltFirstName);
        eltStudent.addContent(eltLastName);

        eltRoot.addContent(eltStudent);

        Document doc = new Document(eltRoot);
        XMLOutputter outputter = new XMLOutputter();
        String xml = outputter.outputString(doc);
        resp.setContentType("application/xml");
        resp.getWriter().println(xml);

    }   
}

1 个答案:

答案 0 :(得分:0)

我建议你建立一个学生对象:

public class Student{

String firstName;
String lastName;

public Student(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
}

然后我会StudentWritter class创建一个包含Student objects的列表并打印出来:

class StudentWritter{

List<Student> listOfStudents;

public StudentWritter(){
  getAllStudents();
}

public List<Student> getAllStudents(){

  ArrayList<Student> listOfStudents= new ArrayList<>();
  while(thereAreStudents){ // I dont know were you get them from :P
    Student aStudent = new Student(firstName, lastName); //makes a Student object
    listOfStudents.add(aStudent); // adds a Student to the List
  }
  this.listOfStudents = listOfStudents; 
}

//afterwards initialise your outputer and print the list :D
public void printStudents(HttpServletResponse resp){
  Document doc = new Document("Students"); //creates a document "Students"
  XMLOutputter outputter = new XMLOutputter();
  resp.setContentType("application/xml"); 

  for(Student aStudent : listOfStudents){
      String outputString = aStudent.getFirstName() + " " + aStudent.getLastName() 
      resp.getWriter().println(outputString);
  }
}

如果您现在初始化StudentWritter class,则所有学生都将存储到ArrayList<Student>,因为方法getAllStudents()位于constructor的{​​{1}}。这意味着如果您要打印所有学生class实例化并解决您的StudentWritter class方法:

printStudents()

对不起所有的错别字,Iam现在没有IDE工作,我很感激编辑。