Pathfinder92
Pathfinder92

Reputation: 137

Adding the root element to a xml document in java

I'm trying to generate a XML file and save it. The following code shows the way i append root element to the document. When i do this an exception was thrown as follows.

Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.

public void comUnitIterator() {
    System.out.println("This is the iterator");
    Document fileDeclarationDocument = documentBuilder();
    if (comUnits != null && comUnits.size() > 0) {

        for (int i=0; i<comUnits.size();i++) {
            CompilationUnit cu=comUnits.get(i);
            SourceCodeClassVisitor classVisitor = new SourceCodeClassVisitor();
            ClassOrInterfaceDeclaration classOrInterface = classVisitor.visit(cu, null);
            Element rootElement = fileDeclarationDocument.createElement("class");
            fileDeclarationDocument.appendChild(rootElement);
            //classVisitor.visit(cu, null);
        }
    }
    createXML(fileDeclarationDocument, "ABC");
}

Can someone please tell me the reason for this exception.

Thank you in advance.

Upvotes: 6

Views: 9240

Answers (2)

Bizmarck
Bizmarck

Reputation: 2688

You're adding a root element for every iteration of this loop:

for (int i=0; i<comUnits.size();i++)

Change your code to something like:

Element rootElement = fileDeclarationDocument.createElement("class");
fileDeclarationDocument.appendChild(rootElement);
for (int i=0; i<comUnits.size();i++) {
     //add children here
 }

There can only be one root element

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500485

You need to create a single root element. Currently you're creating one for each element of comUnits. You should pull this statement:

Element rootElement = fileDeclarationDocument.createElement("class");

... and append it to the document:

fileDeclarationDocument.appendChild(rootElement);

Then in your loop, you can create a new element for each iteration, and append that to the root element. (It's not really clear what you want your XML structure to be, to be honest. With more details on that, we may be able to help you more.)

Upvotes: 2

Related Questions