0

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.

4

1 回答 1

2

您正在调用option.appendChild()并将结果传递给它

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

appendChild()返回新附加的子节点,而不是它附加到的节点。所以你实际上是option.appendChild()用一个文本节点调用的。你要:

Element state = doc.createElement("state");
state.appendChild(doc.createTextNode(paths.get(i)));
option.appendChild(state);
于 2014-07-10T16:25:10.107 回答