I having a problem with the cloneNode tag problem.

NodeList movielist = doc.getElementsByTagName("movie");
    Element child = (Element)movielist.item(6);
    Element newNode = (Element)child.cloneNode(true);
    child.appendChild(newNode);
    newNode.setAttribute("id", "this is newnode");

code above will clone the whole set of thing. but the problem is it colne in wrong tag. i want some thing like this in my xml file.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<movies>
<movie id="1007">
        <title>Interstellar</title>
        <genre>Science Fiction</genre>
        <duration>180 mins</duration>
        </movie>
    <movie id="this is newnode">
        <title>Interstellar</title>
        <genre>Science Fiction</genre>
        <duration>180 mins</duration>
    </movie>
</movies>

but the code above give me something like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<movies>
<movie id="1007">
        <title>Interstellar</title>
        <genre>Science Fiction</genre>
        <duration>180 mins</duration>
    <movie id="this is newnode">
        <title>Interstellar</title>
        <genre>Science Fiction</genre>
        <duration>180 mins</duration>
    </movie></movie>
</movies>

Line 4 replace: movielist.appendChild(newNode);
or if you want to put new node after resource to copy then check if child.nextSibling exist then movielist.insertBefore(newNode, child.nextSibling); otherwise movielist.appendChild(newNode);

Edited 1 Year Ago by AndrisP

movielist.appendChild(newNode);

is not working. its give me error : cannot find symbol movielist.appendChild(newNode)

in the line 1

getElementsByTagName

is not unique selection it's a list. Try movielist[0]
or another way: child.parentNode.appendChild(newNode);

Edited 1 Year Ago by AndrisP

do you mean

NodeList movielist[0] = doc.getElementsByTagName(movielist);

or

NodeList movielist = doc.getElementsByTagName(movielist[0]);



child.parentNode.appendChild(newNode);

same error for this code.

No!

NodeList movielist = doc.getElementsByTagName("movie")[0];

Edited 1 Year Ago by AndrisP

well, it show error array required, but NodeList found on that line

Edited 1 Year Ago by sing1006

Sorry. parentNode in the your example is "movies".
Use child.parentNode.appendChild(newNode); or child.parentNode.insertBefore(newNode, child.nextSibling);

Edited 1 Year Ago by AndrisP

child.parentNode.appendChild(newNode);

error: cannot find symbol child.parentNode.appendChild(newNode)

symbol: variable parentNode
location variable child of type Element

thanks for the help. i figure it out already here is my solution.
by changing

child.appendChild(newNode);

to 

root.appendChild(newNode);

and add line

Element root = doc.getDocumentElement();
This question has already been answered. Start a new discussion instead.