我的源代码需要在一些现有标签之间追加/添加新标签到我在硬盘上的XML文档。我很困惑我需要使用哪种解析器来完成这项任务。
XML文档我看起来类似于:
<school>
<teacher>
<name>XXXXX</name>
<gender>XXXX</gender>
</teacher>
</school>
需要此XML文档:
<school>
<teacher>
<name>XXXXX</name>
<gender>XXXX</gender>
</teacher>
<!--need to append student tag-->
<student>
<name>XXXXXX</name>
<gender>XXXXX</name>
</student>
</school>
所以,请帮助我选择高效的xmlparser来完成这项工作。另外,如果你能告诉我样本源代码来完成这项任务,我很感激。
提前致谢..
答案 0 :(得分:2)
如果我正确理解了这个问题,我假设您正在尝试使用包含教师的xml文档,对于那些教师,您想要添加相应的生。
我建议使用DOM解析器(底部的链接作为参考)。
我已经创建了一些代码,可以让您使用教师信息获取XML文件,并生成一个包含所需结果的新文件。
为方便起见,我使用了过多的评论!
package com.yourpackage.model;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class addStudentsXml {
public static void main(String[] args) throws Exception {
//Create the DocumentBuilderFactory
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//Parse your XML file
Document document = documentBuilder.parse("yourFileName.xml"); //Insert your file name here
//Declare the school that you wish to populate
School school = new School();
//Create the list of teachers
List<Teacher> teachers = new ArrayList<Teacher>();
//Create the list of nodes from the document
NodeList nodeList = document.getDocumentElement().getChildNodes();
//Populate the teacher list with all of the teachers in the XML document
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Teacher newTeacher = new Teacher();
newTeacher.name = node.getAttributes().getNamedItem("name").getNodeValue();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node cNode = childNodes.item(j);
if (cNode instanceof Element) {
String content = cNode.getLastChild().getTextContent().trim();
if(cNode.getNodeName().equals("name")) {
newTeacher.name = content;
} else if(cNode.getNodeName().equals("gender")) {
newTeacher.gender = content;
}
}
}
//Add new teachers to the teacher list
teachers.add(newTeacher);
}
}
//Add your teachers to your school
school.setTeachers(teachers);
//Create the list of students
List<Student> students = new ArrayList<Student>();
//Populate your students here depending upon how your data is feeding them in
//Add your students to your school
school.setStudents(students);
//Now we will start to create the new xml document to be exported
Document newDoc = documentBuilder.newDocument();
//Create the root of the doucment
Element root = newDoc.getDocumentElement();
//Create the school element
Element newSchool = newDoc.createElement("school");
//Add the school to the root of the document
root.appendChild(newSchool);
//For all of the teachers in the teacher list, add their corresponding students
for (Teacher teacher : teachers) {
//Create the teacher element
Element newTeacher = newDoc.createElement("teacher");
//Add the teacher's name
Element teacherName = newDoc.createElement("name");
teacherName.appendChild(newDoc.createTextNode(teacher.getName()));
newTeacher.appendChild(teacherName);
//Add the teacher's gender
Element teacherGender = newDoc.createElement("gender");
teacherGender.appendChild(newDoc.createTextNode(teacher.getGender()));
newTeacher.appendChild(teacherGender);
//Add the teacher to the school
newSchool.appendChild(newTeacher);
for (Student student : students) {
if (student.getTeacherName().trim().equals(teacher.getName().trim())) {
//Create the student element
Element newStudent = newDoc.createElement("student");
//Add the student's name
Element studentName = newDoc.createElement("name");
studentName.appendChild(newDoc.createTextNode(student.getName()));
newStudent.appendChild(studentName);
//Add the student's gender
Element studentGender = newDoc.createElement("gender");
studentGender.appendChild(newDoc.createTextNode(student.getGender()));
newStudent.appendChild(studentGender);
//Add the student to the school
newSchool.appendChild(newStudent);
}
}
}
//Create the transformerFactory, transformer, and the result to be saved to a new file "schoolinfo.xml"
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(newDoc);
StreamResult result = new StreamResult(new File("C://schoolinfo.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
}
public static class School {
private List<Teacher> teachers;
private List<Student> students;
public void setTeachers(List<Teacher> teachers) {
this.teachers = teachers;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public List<Teacher> getTeachers() {
return teachers;
}
public List<Student> getStudents() {
return students;
}
}
public static class Teacher {
private String name = "";
private String gender = "";
public String getName() {
return name;
}
public String getGender() {
return gender;
}
}
public static class Student {
private String studentName = "";
private String studentGender = "";
private String teacherName = "";
public String getName() {
return studentName;
}
public String getGender() {
return studentGender;
}
public String getTeacherName() {
return teacherName;
}
}
}
这应该在您的XML文件中读取(您必须用您的实际文件名替换文件名)并填充教师列表。就学生信息而言,您必须从您从中检索数据的任何位置填充该列表。
一旦该数据可用并正确存储,将创建一个新文档,并且XML应以您希望的形式附加到该文档。此文档将存储到您的C:驱动器中,但您可以更改该路径以将其存储在您喜欢的任何位置。
我使用这些链接作为参考:
MKYong(导出XML文件):here
Stackoverflow(追加节点):here
Java Code Geeks(DOM Parsers):here
如果我的解决方案中有任何需要澄清的内容,请告诉我,我是stackoverflow的新手!
答案 1 :(得分:2)
XOM是最简单的Java XML系统。通过操作XOM树本身可以避免很多混乱。
public void test() throws ParsingException, ValidityException, IOException {
String xml = "<school><teacher><name>XXXXX</name><gender>XXXX</gender></teacher></school>";
String add = "<student><name>XXXXXX</name><gender>XXXXX</gender></student>";
Builder parser = new Builder();
// Parse them.
Document school = parser.build(new ByteArrayInputStream(xml.getBytes()));
Document student = parser.build(new ByteArrayInputStream(add.getBytes()));
// Manipulate - remember to copy.
school.getRootElement().appendChild(student.getRootElement().copy());
// To XML.
System.out.println(school.getRootElement().toXML());
}
打印:
<school><teacher><name>XXXXX</name><gender>XXXX</gender></teacher><student><name>XXXXXX</name><gender>XXXXX</gender></student></school>
即
<school>
<teacher>
<name>XXXXX</name>
<gender>XXXX</gender>
</teacher>
<student>
<name>XXXXXX</name>
<gender>XXXXX</gender>
</student>
</school>
对于重要的项目,它可能是一个更好的解决方案,可以将XML编组到对象中,操作对象并将它们解组回xml(如@KyleStoflet所建议的那样)。
或者 - 您可以使用暴力并直接操纵字符串。这是非常不满意的。
public void test() {
String xml = "<school><teacher><name>XXXXX</name><gender>XXXX</gender></teacher></school>";
String add = "<student><name>XXXXXX</name><gender>XXXXX</gender></student>";
StringBuilder both = new StringBuilder(xml)
.insert(xml.indexOf("</school>"), add);
System.out.println(both);
}