I have the following xml file
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee ID="1">
<Firstname>David</Firstname >
<Lastname>Berkley</Lastname>
<Age>30</Age>
<Salary>25001</Salary>
</Employee>
<Employee ID="2">
<Firstname>Ashton</Firstname>
<Lastname>Hutt</Lastname>
<Age>22</Age>
<Salary>26000</Salary>
</Employee>
</Employees>
I wish to add more fields in this XML file like :
1) New Employee.
2) New Employee Details like Address which is not present here.
3) Delete Previous record.
After taking the appropriate values from the user I may modify the XML accordingly through my java code.
Suppose after doing point number 1 and 2 my new xml becomes...
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee ID="1">
<Firstname>David</Firstname >
<Lastname>Berkley</Lastname>
<Age>30</Age>
<Salary>25001</Salary>
<Address>10th cross,Park Avenue</Address>
</Employee>
<Employee ID="2">
<Firstname>Ashton</Firstname>
<Lastname>Hutt</Lastname>
<Age>22</Age>
<Salary>26000</Salary>
</Employee>
<Employee ID="3">
<Firstname>Holly</Firstname>
<Lastname>Becker</Lastname>
<Age>24</Age>
<Salary>30000</Salary>
</Employee>
</Employees>
How can I achieve this Using the StAX parser? Please help me by giving some appropriate tips and code as to how I may achieve this. :(
EDIT 1
This is my function which I wish to call while adding any new record.
public void addNewEmployee(XMLStreamWriter writer,String newID, String firstN, String lastN, String age, String salary)
{
try
{
writer.writeStartDocument();
writer.writeStartElement("Employee");
writer.writeAttribute("ID", newID);
writer.writeStartElement("Firstname");
writer.writeCharacters(firstN);
writer.writeEndElement();
writer.writeStartElement("Lastname");
writer.writeCharacters(lastN);
writer.writeEndElement();
writer.writeStartElement("Age");
writer.writeCharacters(age);
writer.writeEndElement();
writer.writeStartElement("Salary");
writer.writeCharacters(salary);
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
writer.close();
// System.out.println("New Record Added");
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
EDIT 2 Another issue I am facing is while traversing the previous XML.... How can i traverse it so that my cursor goes right after this block
<Employee ID="2">
<Firstname>Ashton</Firstname>
<Lastname>Hutt</Lastname>
<Age>22</Age>
<Salary>26000</Salary>
</Employee>
and before the line </Employees>
Because I need to call the addNewEmployee()
at the proper moment.