我正在尝试使用DOM从Java创建xml文档。但是我不确定我在哪里。我在线程“主” org.w3c.dom.DOMException中收到错误Exception:HIERARCHY_REQUEST_ERR:试图在不允许的节点上插入节点。请尝试解决此问题。我需要创建单独的xml文件,并在该文件中写入我的预期输出
Mainclass
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
int unit=0;
ArrayList<Books> bookslist = new ArrayList<Books>();
System.out.println("Enter the amount of books need to add");
unit = obj.nextInt();
Books books = new Books();
for(int i=0;i<unit;i++)
{
System.out.println("enter the book name");
books.setName(obj.next());
System.out.println("enter the author name");
books.setAuthor(obj.next());
System.out.println("enter the book price");
books.setPrice(obj.nextFloat());
bookslist.add(books);
}
CreateXml createxml = new CreateXml(bookslist,unit);
}
}
CreateXml.java
public CreateXml(ArrayList<Books> bookslist, int unit) {
try{
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
for(int i=0;i<unit;i++)
{
Element rootElement = document.createElement("BookList");
document.appendChild(rootElement);
Element book= document.createElement("Book");
rootElement.appendChild(book);
Element bookname=document.createElement("Name");
bookname.appendChild(document.createTextNode(bookslist.get(i).getName()));
book.appendChild(bookname);
Element authorname = document.createElement("Author");
authorname.appendChild(document.createTextNode(bookslist.get(i).getAuthor()));
book.appendChild(authorname);
Attr attribute = document.createAttribute("Price");
attribute.setValue(String.valueOf(bookslist.get(i).getPrice()));
book.appendChild(attribute);
}
TransformerFactory transformerfactory = TransformerFactory.newInstance();
Transformer transformer = transformerfactory.newTransformer();
DOMSource domSource = new DOMSource(document);
System.out.println(document);
StreamResult streamResult = new StreamResult(new File("createdFiles/createFile.xml"));
transformer.transform(domSource, streamResult);
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm expecting this output
<BookList>
<Book>
<Name>vdg</Name>
<Price>89.26</Price>
<Author>bfkj</Author>
</Book>
<Book>
<Name>vdg</Name>
<Price>89.26</Price>
<Author>bfkj</Author>
</Book>
</BookList>