简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM