InsertElement dom4j Q

E

Emmanuel

I am trying to use the method from the dom4j Library to insert new
element it to an existing xml but I keep getting an error. Is any one
familiar with the dom4j Library? I need help. I am new to Dom4j.
Inserting elements sometimes it's necessary to insert an element in a
existing XML Tree. This is easy to do using dom4j Collection API.
Need help thanks

public void insertElementAt(Element newElement, int index) {
Element parent = this.element.getParent();
List list = parent.content();
list.add(index, newElement);
}

public void testInsertElementAt() {

//insert an clone of current element after the current element
Element newElement = this.element.clone();
this.insertElementAt(newElement,
this.root.indexOf(this.element)+1);

// insert an clone of current element before the current element
this.insertElementAt(newElement,
this.root.indexOf(this.element));
}
 
M

Mike Schilling

Emmanuel said:
I am trying to use the method from the dom4j Library to insert new
element it to an existing xml but I keep getting an error.

Don't tell us what the error is; we're keen to guess.
 
E

Emmanuel

I am sorry about that this is the error I get I am passing in a value
the element is not null cause when I print the element it is fine. When
I try to insert it to an existing xml I get this error. I don't know
why I am getting a null pointerException .
org.dom4j.tree.DefaultElement@60420f [Element: <a attributes:
[]/>]Exception in thread "main" java.lang.NullPointerException
at org.demo.tester1.insertElementAt(tester1.java:130)
at org.demo.first.main(first.java:25)
 
E

Emmanuel

This is my modify code

public void insertElementAt(Element newElement, int index)
{
try {
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read("C:/Documents and
Settings/a411973/Desktop/java/try.xml");
Element element = doc.getRootElement();
Element parent = element.getParent();
List list = parent.content();
list.add(index, newElement);
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(
new FileWriter( "C:/Documents and
Settings/a411973/Desktop/java/try2.xml", true),format
);
writer.write( newElement );
writer.close();

} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}

}



}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top