-3

I am trying to add elements to xml. I followed Java DOM - Inserting an element, after another but that did not work for me. Here is my code:

Element e = dom.createElement("mapping");
e.setAttribute("resource", "/some/path/to/file");
Element lastChild = (Element)nList.item(nList.getLength()-1);
Element parent= (Element)nList.item(nList.getLength()-1).getParentNode();

lastChild.getParentNode().insertBefore(e, lastChild);

I also tried parent.appendChild(e); but none of them work. It doesn't seem like there is problem with the code. What could be the problem?

I am using Netbeans on macosx. Is this because of file permissions ?

Community
  • 1
  • 1
happyHelper
  • 119
  • 8
  • 1
    "*It doesn't seem like there is problem with the code.*" What makes you think that? – dimo414 Apr 07 '15 at 00:26
  • Because I have tested it a couple of times and there are no errors. Also there arent any logical flaws and this same snippet seems to work for others. – happyHelper Apr 07 '15 at 00:29
  • A lack of errors simply means the code successfully does *something*, it doesn't mean it does *what you want*. If the same snippet works for others, there's clearly a "logical" flaw in your code, though perhaps not in that snippet in particular. – dimo414 Apr 07 '15 at 00:32
  • For instance, how do you know this code isn't "working"? It's likely `e` is in fact being inserted before `lastChild`, but whatever you're doing to verify this is incorrect. – dimo414 Apr 07 '15 at 00:35
  • *"Is this because of file permissions?"* Maybe? We're not on your computer, so we can't answer specifics about your environment. Try writing a quick test that reads the file as text; if it reads it, you have read permission. – dimo414 Apr 07 '15 at 00:36
  • Shouldnt I see an entry in xml file. There is none. Also when I do getLastChild I dont see the new addition. – happyHelper Apr 07 '15 at 00:43
  • I have read write permissions. – happyHelper Apr 07 '15 at 00:51
  • You should only see change *in the file* if you write your data back to the file. The code snippet you shared is not editing the file, it is modifying an in-memory DOM. – dimo414 Apr 07 '15 at 01:09
  • Also you're calling `.insertBefore()` - the last child will still be `lastChild` after that call. – dimo414 Apr 07 '15 at 01:10
  • I tested lastChild with appendChild to parent. Anyways I think I got the answer I was looking for, I will look into how to write DOM modified data back to file. If you can post that as an answer I will accept it. Thanks. – happyHelper Apr 07 '15 at 01:16

1 Answers1

0

The Elements you are working with are a DOM in memory, they are not directly tired to your file contents. The code snippet you posted only modifies that DOM. You will only see change in the file if you write your data back to the file.

dimo414
  • 47,227
  • 18
  • 148
  • 244