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));
}
Mike Schilling - 23 Oct 2006 21:09 GMT
>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.
Emmanuel - 02 Nov 2006 22:12 GMT
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)
> >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.
Emmanuel - 02 Nov 2006 22:16 GMT
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();}
}
}