Generating XML with an arbitrary number of nodes

I'm new to working with java. I'm trying to write out an XML file which has this form:

<option>
    <name>CompilerOptions</name>  
       <state>Directory1</state>
       <state>Directory2</state>
       <state>Directory3</state>
    </name>
</option>

The number of directories is arbitrary and depends on selections by the users.Here's the section of the code which should generate the XML file.

    for(int i = 0; i < paths.size(); i++) {
    option.appendChild(doc.createElement("state").appendChild(doc.createTextNode(paths.get(i))));
    }
    child.appendChild(option);

The problem is that the output doesn't have the tags, which I expected to be created by doc.createElement("state"). Why aren't those nodes being created?

here's an example:

<option>
    <name>CompilerOptions</name>
    Directory1
    Directory2
    Directory3
</option>

Thanks for the help.

Jon Skeet
people
quotationmark

You're calling option.appendChild() and passing it the result of

doc.createElement(...).appendChild(...)

But appendChild() returns the newly-appended child, not the node it was appended to. So you're actually calling option.appendChild() with a text node. You want:

Element state = doc.createElement("state");
state.appendChild(doc.createTextNode(paths.get(i)));
option.appendChild(state);

people

See more on this question at Stackoverflow