编辑:发现问题 - 我正在将元素添加到 doc,而它应该被添加到“rootElement”。现在工作。如果你们对如何使我的代码更好有任何进一步的建议,请告诉我
在下面的代码中,我尝试手动输入一个 XML 文件,然后用一个函数稍微简化它。
我收到错误“HIERARCHY_REQUEST_ERR”。我知道问题出在我的函数底部的以下代码,但我不知道如何处理它。当我摆脱 doc.appendChild(staff); 时,我摆脱了这个问题,但它显然没有添加新条目。
元素人员 = doc.createElement("Staff"); doc.appendChild(员工);
谢谢看!!
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;
public class createXMLfile {
public static void main(String [] args) throws ParserConfigurationException, TransformerException{
String address = "/home/leor/workspace/Test/Files/src/outputFile.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element rootElement = doc.createElement("Company");
doc.appendChild(rootElement);
// EMPLOYEE #1
//-----------------------------------------------------------//
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
staff.setAttribute("id", "1");
Element firstName = doc.createElement("First_Name");
firstName.appendChild(doc.createTextNode("John"));
staff.appendChild(firstName);
Element lastName = doc.createElement("Last_Name");
lastName.appendChild(doc.createTextNode("Smith"));
staff.appendChild(lastName);
Element salary = doc.createElement("Salary");
salary.appendChild(doc.createTextNode("120,000"));
staff.appendChild(salary);
//-----------------------------------------------------------//
createNewEntry(doc, "2", "Leo", "Benner", "90,000");
createNewEntry(doc, "3", "Sarah", "Gordon", "75,000");
createNewEntry(doc, "4", "Scott", "Jones", "55,000");
//-----------------------------------------------------------//
TransformerFactory f = TransformerFactory.newInstance();
Transformer tf = f.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult r = new StreamResult(new File(address));
tf.transform(source, r);
System.out.println("File created.");
}
//-----------------------------------------------------------//
public static void createNewEntry(Document doc, String id, String fName, String lName, String sal){
Element staff = doc.createElement("Staff");
doc.appendChild(staff);
staff.setAttribute("id", id);
Element firstName = doc.createElement("First_Name");
firstName.appendChild(doc.createTextNode(fName));
staff.appendChild(firstName);
Element lastName = doc.createElement("Last_Name");
lastName.appendChild(doc.createTextNode(lName));
staff.appendChild(lastName);
Element salary = doc.createElement("Salary");
salary.appendChild(doc.createTextNode(sal));
staff.appendChild(salary);
}
}