I have to Parse XML as of now i have used SAX parser now i have to display, edit it and in end create XML the issue is now how do i do that with SAX Parser because it does not have that feature. I am in tough situation, also i have searched things about dom4j and DOM. My code is shown below.
public class XmlBack extends DefaultHandler {
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("VarGroup")) {
varGroupVariables = new HashMap<String, List<VarGroupVariable>>();
}else if (qName.equalsIgnoreCase("Variable")) {
varGroupVariable = new VarGroupVariable();
nameAttribute = attributes.getValue("Name");
varGroupVariable.setName(nameAttribute);
}else if (qName.equalsIgnoreCase("TYP")) {
btype = true;
}else if (qName.equalsIgnoreCase("VALUE")) {
bvalue = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
String vtype = null;
if (btype) {
vtype = new String(ch, start, length);
varGroupVariable.setType(vtype);
btype = false;
}
Double value = null;
if (bvalue) {
String vvalue = new String(ch, start, length);
try {
value = Double.valueOf(vvalue);
} catch (NumberFormatException ne) {
value = 0d;
}
varGroupVariable.setValue(value);
bvalue = false;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("Variable")) {
String varGroupVariableName = varGroupVariable.getName().split("\\.")[0];
String name = varGroupVariableName.substring(0,varGroupVariableName.length() - 1);
String name1= varGroupVariableName = varGroupVariable.getName().split("\\.")[1];
System.out.println(name1);
List<VarGroupVariable> varGroupVariablesList;
if(varGroupVariables.containsKey(name)) {
varGroupVariablesList = varGroupVariables.get(name);
}else {
varGroupVariablesList = new ArrayList<VarGroupVariable>();
}
int serial = varGroupVariablesList.size();
varGroupVariable.setSerial(++serial);
varGroupVariablesList.add(varGroupVariable);
varGroupVariables.put(name, varGroupVariablesList);
//System.out.println(name+"\n");
}
}
private int no = 1;
boolean bcore,bmold,bvalue,btype = false;
String nameAttribute;
Map<String, List<VarGroupVariable>> varGroupVariables;
VarGroupVariable varGroupVariable;
}
Unless your XML isn't unreasonably complex, or if you have a schema for it available) the easiest option is probably JAXB. There are several tutorials around, for example this. Of course, StackOverflow is also a good source for JAXB knowledge.