从MySQL数据库读取数据并将其写入XML文件。 AM收到以下错误" HIERARCHY_REQUEST_ERR:尝试插入不允许的节点。 " 任何想法如何解决这个
private static Document buildCustomerXML(ResultSet _customerRS, ResultSet contractRS) throws Exception
{
Document xmlDoc = new DocumentImpl();
/* Creating the root element */
Element rootElement1 = xmlDoc.createElement("Contracts");
xmlDoc.appendChild(rootElement1);
while(contractRS.next()){
Element contract = xmlDoc.createElement("Contract");
/* Build the CustomerId as a Attribute*/
contract.setAttribute("ID", _customerRS.getString("ID"));
rootElement1.appendChild(contract);
}
Element rootElement = xmlDoc.createElement("Employees");
xmlDoc.appendChild(rootElement);
while(_customerRS.next())
{
Element employee = xmlDoc.createElement("Employee");
/* Build the CustomerId as a Attribute*/
employee.setAttribute("id", _customerRS.getString("id"));
/* Creating elements within customer DOM*/
Element contractid = xmlDoc.createElement("ContractID");
Element lastName = xmlDoc.createElement("Name");
Element skills = xmlDoc.createElement("Skills");
Element skill = xmlDoc.createElement("Skill");
/* Populating Customer DOM with Data*/
contractid.appendChild(xmlDoc.createTextNode(_customerRS.getString("Contractid")));
lastName.appendChild(xmlDoc.createTextNode(_customerRS.getString("last")));
skill.appendChild(xmlDoc.createTextNode(_customerRS.getString("Skill")));
/* Adding the firstname and lastname elements to the Customer Element*/
employee.appendChild(contractid);
employee.appendChild(lastName);
skills.appendChild(skill);
employee.appendChild(skills);
/* Appending Customer to the Root Class*/
rootElement.appendChild(employee);
}
return xmlDoc;
}

答案 0 :(得分:0)
问题在于您要创建两个根元素:
Element rootElement1 = xmlDoc.createElement("Contracts");
xmlDoc.appendChild(rootElement1);
和
Element rootElement = xmlDoc.createElement("Employees");
xmlDoc.appendChild(rootElement);
Document
只能有一个顶级元素。您应该创建一个根元素(例如" ContractsEmployees")并将这两个元素作为子元素追加。或者您可以为每个元素创建两个单独的文档。
此外,这不是创建文档的正确方法(您使用内部类)。使用文档构建器。
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document xmlDoc = builder.newDocument();