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>

Recommended Answers

All 9 Replies

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

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

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

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

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

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();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.